reactjs 如何让数据库数据在第一次呈现时显示?

zpqajqem  于 5个月前  发布在  React
关注(0)|答案(1)|浏览(65)

我一直在做一个日历,它会在每个框上显示数据库中的信息,如果该日期有任何内容。如果没有,它就是空白的。我无法解决的问题是每个框都是空的。然后当我修改代码并保存它时,它最终会显示在框中。
当我保存我的代码并再次呈现时,它就从undefined变成了数据库中的实际数据,就像我提到的那样。
在使用数据库之前,我使用的是本地存储,它很好用。在userListings的useState中,我使用了一个三进制数据和本地存储中的数据,如果没有数据,则使用一个空数组。数据库是否可以这样做?或者让所有内容都出现的最佳解决方案是什么?
CreateListing.jsx

const [nav, setNav] = useState(0);
  const [days, setDays] = useState([]);
  const [dateDisplay, setDateDisplay] = useState('');
  const [clicked, setClicked] = useState();
  const [isLoading, setIsLoading] = useState(true);

  const [showListingsError, setShowListingsError] = useState(false);
  const { currentUser} = useSelector(state => state.user);
  const [userListings, setUserListings] = useState([]);

 const eventForDate = date => userListings.find(e => e.date === date);
 console.log('eventforDate', eventForDate())

useEffect(() => {
    const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    const today = new Date();
    
    if (nav !== 0) {
      today.setMonth(new Date().getMonth() + nav);
    }

    const month = today.getMonth()  //Gives you the month number
    const day = today.getDate() //Gives you the day number
    const year = today.getFullYear()    //Gives you the year 

    const firstOfMonth = new Date(year, month, 1);  //Gives you the date. Ex: Sat Oct 01 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
    const fullDaysInMonth = new Date(year, month + 1, 0).getDate(); //Gives you the number of days in the month

    const dateString = firstOfMonth.toLocaleDateString('en-us', {
      weekday: 'long',
      year: 'numeric',
      month: 'numeric',
      day: 'numeric',
    });

    setDateDisplay(`${today.toLocaleDateString('en-us', {month: 'long'})} ${year}`)
  
    let dayWithZ = 0;
    let monthWithZ = 0;
  
    // Gives you the amount of days before the first day of the month on the first week
    const paddingDays = weekdays.indexOf(dateString.split(',')[0]);   
    
    const daysArr = [];

    for (let i = 1; i <= paddingDays + fullDaysInMonth; i++) {

      if (i - paddingDays < 10) {
        dayWithZ = ('0' + (i - paddingDays)).slice(-2) 
        
      } 
    
      if (i -paddingDays >= 10){
        dayWithZ = i-paddingDays;
      }

      if ((month + 1) < 10) {
            monthWithZ = ('0' + (month + 1)).slice(-2)  
      } 

      if ((month + 1) >= 10) {
        monthWithZ = month + 1;
      }
      let dayStringTest = `${year}-${monthWithZ}-${dayWithZ}`;
  
      if (i > paddingDays) {
        daysArr.push({
          value: i - paddingDays,
          event: eventForDate(dayStringTest),
          isCurrentDay: i - paddingDays === day && nav === 0,
          date: dayStringTest,
        });
      } else {
        daysArr.push({
        value: 'padding',
        event: null,
        isCurrentDay: false,
        date: '',
        });
      }

    }
    setDays(daysArr);

  }, [setDays, nav]);

 useEffect(() => {

    async function fetchData() {
    try {
      setShowListingsError(false);
        const res = await fetch(`/api/user/entries/${currentUser._id}`);
        const data = await res.json();
        if (data.success === false) {
          setShowListingsError(true);
          return;
        }
        setUserListings(data);
        setIsLoading(false);
        console.log('try', userListings)
        console.log('days', days)
    } catch (error) {
      setShowListingsError(true);
    }
  }
    fetchData();
    

  }, [])

return (
    <>
  
      <div>
          <section id="calendar" className="flex flex-wrap">
            {days && days.map((d, index) => (
              <Day 
                key={index} 
                day={d} 
                event={userListings}
                onClick={() => {
                  // console.log("d", d)
                  // console.log("d.date", d.date)
                  // console.log("Click")
                  // console.log("EFD", eventForDate)
                  if (d.value !== 'padding') {
                    setClicked(d.date);
                  }
                }} 
              />
              //  <div>{d?.event?.title}</div>
            ))}
         
    </div>
    </>
  )

字符串
Day.jsx

export const Day = ( {day, onClick}) => {
    const className = `white no-underline flex h-[100px] w-[100px] bg-blue-500 p-1 cursor-pointer rounded-sm m-0.5 ${day.value === 'padding' ? 'padding' : ''} ${day.isCurrentDay ? 'rounded-sm border-2 border-blue-700' : ''}`;
    console.log("Day component", day)
    console.log("Day event", day.event)
    return (
        <div onClick={onClick} className={className}>
            {day.value === 'padding' ? '' : day.value}

            {day.event && <div className="w-full bg-blue-200 text-center rounded-sm">{day.event.title}</div>}

        </div>
    )
}


我尝试在返回中使用三元运算符isLoading,但这不起作用。

kxe2p93d

kxe2p93d1#

第一个useEffect应该在userListings状态改变时呈现。因此,需要将userListings状态添加到第一个(相关)useEffect的依赖项中:

useEffect(() => {
...
}[setDays, nav, userListings]); // <== Added here

字符串
如果不添加它,useEffect是独立于userListings状态呈现的。当它呈现时,userListings状态具有默认值,定义为empty array []。因此,eventForDate函数返回undefined,因为它找不到默认状态的任何记录(空数组[])。
简而言之,将userListings依赖项状态添加到相关的useEffect可以解决这个问题。

相关问题