我一直在做一个日历,它会在每个盒子上显示数据库中的信息,如果那个日期有什么事情的话.如果什么都没有,那么它就是空白的.我无法解决的问题是每个盒子都是空的.然后,当我对代码进行更改并保存它时,它最终会显示在框中.

我对事件未定义.当我保存代码并再次呈现时,它从未定义变为数据库中的实际数据,就像我提到的那样.

在使用数据库之前,我使用的是本地存储,它起作用了.在UserListings的useState中,我使用了一个包含本地存储中数据的三元数组,如果没有数据,则使用一个空array.使用数据库可以做到这一点吗?或者,让一切都显现出来的最佳解决方案是什么?

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>
    )
}

我try 在返回中使用带有isLoding的三元运算符,但不起作用.

推荐答案

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

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

在没有添加的情况下,useEffect独立于userListings状态进行渲染.并且当它被呈现时,userListings状态具有定义为empty array []的缺省值.因此,eventForDate函数返回未定义的原因,因为它找不到默认状态(空数组[])的任何记录.

简而言之,将userListings依赖状态添加到相关的useEffect就可以解决这个问题.

Reactjs相关问答推荐

将cy.get()与动态类名一起使用?

单击空白区域时,Reaction Multiple下拉组件不关闭

我想删除NextJs中的X轴标签APEXCHARTS

在Reaction常量函数中未更新状态变量

为什么查询错误在处理后仍出现在控制台中?RTK查询+ React

useState导致对函数的无休止调用

.populate() 方法在 mongodb 中不起作用

是否可以直接在 jsx 标签上使用 CSS 定义的 colored颜色 ?

这个简单的React组件为什么会多次渲染?

如何到达类组件中的状态?

从服务器获取数据时未定义,错误非法调用

RTK 查询Mutations 在 StrictMode 中执行两次

Cypress ,重试不再附加到 DOM 的元素

React Router v6 - 访问嵌套路由和处理手写 url 的正确方法

React Router 6.4CreateBrowserRouter子元素不显示

如何使用 cypress 获取 MUI TextField 的输入值?

是什么导致了这个令人惊讶的数组导致 React

Lodash 在命名导入中导入整个包

a.active 类在导入 x.scss 文件时有效,但在使用 x.module.scss 时无效

仅react material 表前端分页