reactjs - 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) 显示它是一个对象,但也会打印“4”。如您所见,它执行了两次,我也不确定为什么。
解决方案
.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
]);
}
}, []);
推荐阅读
- python - 尝试将对象属性映射到不同名称的数据库列
- android - 是否可以进行多个并行调用并接受使用 Kotlin Flow 返回的第一个?
- c# - 如何在单元测试中验证 Flurl Http 中的请求正文内容?
- c# - Blazor:双向绑定错误 - 仅第一次工作
- bash - linux bash在文件中的可变行号处插入文本
- c++ - C++ 中的 WindowsIdentity.GetCurrent().IsSystem
- c - 更新图像时 GTK 内存泄漏
- mfc - MFC:从 CView 访问 m_wndToolBar?
- android - Android Studio FreeMarker 模板(按插件)
- c# - EWS 管理 API - 创建约会时未将对象引用设置为对象的实例