由于一些奇怪的原因,当尝试使用 setState (hooks) 更改数组时,我收到以下错误:
无法读取未定义的属性“过滤器”。
尝试控制台记录阵列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;
翻翻过去那场雪
红颜莎娜
RISEBY
相关分类