由于某些奇怪的原因,当尝试使用setState(挂钩)更改数组时,出现以下错误:
无法读取未定义的属性“过滤器”。
尝试在控制台中记录阵列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;
答案 0 :(得分:1)
问题是您将计数数据设置不正确。
请执行以下操作。
setCounters({ data: counters });
答案 1 :(得分:0)
错误在handleDecrement
和handleIncrement
const counters = [...count.data];
...
setCounters(counters);
在您的初始状态下,count
是具有data
属性的对象。
setCounters(counters)
时,将count
设置为数组,然后,您尝试在render方法中从.data
访问count
,但这就是undefined
,这会导致错误。
您需要更改
setCounters(counters); // set count as an array
收件人
setCounters({data: counters}); // set count as an object with property 'data' as an array
答案 2 :(得分:0)
在某些方法中,您将counters
状态设置为数组。但是在初始化中,您存储在counters
中的是带有 data 属性(是数组)的对象。
当您调用handleDelete
方法时,您将在counters
中存储一个数组。因此,当重新渲染组件时,它将尝试调用filter
中的counters.data
方法,但是counter.data
当时不存在。
要解决此问题,您可以初始化counters
状态,使其为数组:
const [count, setCounters] = useState([
{ id: 1, value: 4, },
{ id: 2, value: 0, },
{ id: 3,value: 0, },
{ id: 4, value: 0, },
]);
并在其余代码中考虑到count
不再具有data
属性。
另一种解决方案是更新count
状态,以保持原始结构。 handleDelete
方法如下:
const handleDelete = counterId => {
const counters = count.data.filter(c => c.id !== counterId);
setCounters({ data: counters });
};