简体   繁体   English

更新反应状态

[英]Updating React State

I am having trouble updating the state in the Parent component.我在更新Parent组件中的状态时遇到问题。 I have React functional components with this structure:我有这种结构的 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;

...and a Child component: ...和一个子组件:

//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;

With this setup, I can't delete that particular array in the state value by clicking on the 'Click Me!'使用此设置,我无法通过单击“单击我!”来删除状态value中的该特定数组。 button.按钮。 Why is this happening?为什么会这样? Is there something that I missed?有什么我错过的吗?

Edit : I forgot to put the import statement for the Button in the child.js code example, and the const newValue .编辑:我忘了把Button的 import 语句放在child.js代码示例中,以及const newValue This isn't the source of the problem as I have the proper import and variable declaration in the original file.这不是问题的根源,因为我在原始文件中有正确的导入和变量声明。

You missed the button tag.你错过了button标签。 here is code sandbox working URL这是代码沙箱工作 URL

You working example 你的工作示例

click the button and see the console.单击按钮并查看控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM