gpt4 book ai didi

javascript - 使用钩子(Hook)更改状态返回无法读取未定义的属性 'filter'

转载 作者:行者123 更新时间:2023-11-30 19:29:24 24 4
gpt4 key购买 nike

由于某些奇怪的原因,在尝试使用 setState( Hook )更改数组时出现以下错误:

Cannot read property 'filter' of undefined.

尝试控制台记录数组 count 并且我得到了所有列出的项目。

单击 handleDelete 事件会出现该错误。

我是否以错误的方式使用 React Hooks?

import React, { useState } from 'react';

// Components
import NavBar from './components/navbar';
import Counters from './components/counters';

import './App.css';

const App = () => {
const [count, setCounters] = useState({
data: [
{
id: 1,
value: 4,
},

{
id: 2,
value: 0,
},

{
id: 3,
value: 0,
},

{
id: 4,
value: 0,
},
],
});

const handleIncrement = counter => {
const counters = [...count.data];
const index = counters.indexOf(counter);

counters[index] = { ...counter };
counters[index].value++;

setCounters(counters);
};

const handleDecrement = counter => {
const counters = [...count.data];
const index = counters.indexOf(counter);

counters[index] = { ...counter };
counters[index].value--;

setCounters(counters);
};

const handleReset = () => {
const counters = count.data.map(c => {
c.value = 0;
return c;
});

setCounters(counters);
};

const handleDelete = counterId => {
const counters = count.data.filter(c => c.id !== counterId);

setCounters(counters);
};

return (
<React.Fragment>
<NavBar
totalCounters={count.data.filter(c => c.value > 0).length}
/>
<main className="container">
<Counters
onReset={handleReset}
onDelete={handleDelete}
onIncrement={handleIncrement}
onDecrement={handleDecrement}
counters={count.data}
/>
</main>
</React.Fragment>
);
};

export default App;

最佳答案

错误在handleDecrementhandleIncrement

const counters = [...count.data];
...
setCounters(counters);

在你的初始状态,countdata 的对象属性(property)。当你setCounters(counters) , 你设置 count作为一个数组,之后,您尝试访问 .data来自 count在 render 方法中,但那是 undefined ,导致错误。

你需要改变

setCounters(counters); // set count as an array

setCounters({data: counters}); // set count as an object with property 'data' as an array

关于javascript - 使用钩子(Hook)更改状态返回无法读取未定义的属性 'filter',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56588253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com