我无法更新 Parent
组件中的状态。我有这种结构的 React 功能组件:
//parent.js
import React, { useState } from 'react';
import Child from './child.js';
const Parent = () => {
const [ value, setValue ] = useState([
{name:['tutorial', 1, 'langkah'], value:"ABC"},
{name:['tutorial', 2, 'langkah'], value:"DEF"},
{name:['tutorial', 3, 'langkah'], value:"GHI"}
]);
const deleteY = (data) => {
const newValue = value.filter(obj => !obj.name.includes(data));
setValue(newValue);
}
return (
<Child deleteX={deleteY} />
)
}
export default Parent;
...和一个子组件:
//child.js
import React from 'react';
import Button from 'antd/es/button'; //edited
const Child = ({deleteX}) => {
let x = 1;
return (
<Button onClick={() => deleteX(x)}>Click Me!</Button>
)
}
export default Child;
使用此设置,我无法通过单击“单击我!”来删除处于 value
状态的特定数组。按钮。为什么会这样?有什么我错过的吗?
编辑:我忘记将 Button
的导入语句放在 child.js
代码示例中,以及 const newValue
。这不是问题的根源,因为我在原始文件中有正确的导入和变量声明。