首页 > 解决方案 > react useState 和 setState 声明 calendarList.push 不是函数

问题描述

React 新手。我试图保持一个跟踪一系列日历事件的状态。我将状态设置为某个 dummyData,如果将新的日历事件传递给 UserEvents(props),那么我想将其添加到 calendarList 状态。

它给出了一个错误,即 calendarList.push() 不是一个函数。当我 console.log 它是一个数组,所以我不明白为什么我不能在它上面使用 push() 方法。

import React, { useEffect, useState } from 'react';
import Countdown from '../countdown/Countdown';

function UserEvents(props){
    let dummyData = [
        {name: "birthday", date: '03/20/2021'},
        {name: "christmas", date: '12/25/2020'},
        {name: "thanksgiving", date: '11/26/2020'}
      ]
    
    const [calendarList, setCalendarList] = useState(dummyData);
  
    if(props.calendarItem){
        setCalendarList(calendarList.push( props.calendarItem ));
    }

    return (
        <div className="App">
          {
            calendarList.map((item, index) => {
              return(
                <Countdown name={item.name} date={item.date}></Countdown>
              )  
            })
          }
        </div> 
      )
}

export default UserEvents; 

如果你 console.log(calendarList)

如果你 console.log(calendarList) 显示它是一个对象,但也会打印“4”。如您所见,它执行了两次,我也不确定为什么。

标签: reactjssetstate

解决方案


.push有2个问题:

  • 它返回数组的新长度,所以
setCalendarList(calendarList.push( props.calendarItem ));

会做类似的事情setCalendarList(4)

  • 它改变现有的数组(在 React 中从不改变状态)

您还setCalendarList无条件地调用每个渲染。

更改它,使初始状态包括calendarItem

const [calendarList, setCalendarList] = useState([
  ...dummyData,
  ...(props.calendarItem ? [props.calendarItem] : [])
]);

(请参阅在 JavaScript 中有条件地在 Array 中添加元素

您也可以使用您的原始代码,但不要if使用效果挂钩:

useEffect(() => {
  if (props.calendarItem) {
    setCalendarList([
      ...calendarList,
      props.calendarItem
    ]);
  }
}, []);

推荐阅读