简体   繁体   English

父 state 更改时子组件不更新

[英]Child component not updating when parent state changes

I have the following child component:我有以下子组件:

    class Adjust extends Component {
        render() {
        const { values, toggleSelector, SELECTOR } = this.props;
        console.log("values are", values"); //this is only being entered once right now
        
        return(
        <div
        key={values}
        style={{
          marginBottom: "25px",
          width: "80vw",
        }}>
         <button
                buttonSelected={values[index]?.add}
                onClick={() => {
                  toggleSelector(index, SELECTOR.ADD);
                }}
          >
         "Add"
        </button>
       </div>
      )}}

And this is how I pass props to this child这就是我将道具传递给这个孩子的方式

<Adjust  values={values} SELECTOR={SELECTOR} toggleSelector={this.toggleSelector}> </Adjust>

I have a console log in my toggleSelector function in my parent component, which shows that it is being entered, but even though the state is changing, the render of Adjust component is not being entered again.我在我的父组件中的toggleSelector function 中有一个控制台日志,这表明它正在输入,但即使 state 正在更改, Adjust组件的渲染也不会再次输入。

I have tried adding a key to it but that didn't help.我曾尝试为其添加密钥,但没有帮助。

This is the toggleSelector function这是切换选择toggleSelector

      toggleSelector(index, selector) {
        console.log("enter");
        let { values } = this.state;
        values[index][selector] = true;
        if (selector === SELECTOR.ADD) {
          values[index].subtract = false;
        } else if (selector === SELECTOR.SUBTRACT) {
          values[index].add = false;
        } 
        this.setState({
          values,
        });  

}

This was all working fine when Adjust was not a child component but within the parent.当 Adjust 不是子组件而是在父组件中时,这一切都可以正常工作。 Had to make it a child for better code readability必须使它成为一个孩子以获得更好的代码可读性

You don't manage values like an immutable variable, values is the same array between renders, you only update it's content.您不会像不可变变量那样管理valuesvalues是渲染之间的同一个数组,您只需更新它的内容。

You can find more information there Correct modification of state arrays in React.js您可以在 React.js 中正确修改 state arrays找到更多信息

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

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