【问题标题】:react useState and setState claims calendarList.push is not a functionreact useState 和 setState 声明 calendarList.push 不是函数
【发布时间】:2020-10-29 17:11:11
【问题描述】:

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) 显示它是一个对象,但也会打印“4”。如您所见,它会执行两次,我也不确定为什么。

【问题讨论】:

    标签: reactjs setstate


    【解决方案1】:

    .push有2个问题:

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

    会做类似setCalendarList(4)的事情

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

    您还在每次渲染时无条件地调用setCalendarList

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

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

    (见Add elements inside Array conditionally in JavaScript

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多