第一个方法触发后,React不会改变状态

问题描述 投票:1回答:2

在我的React应用程序中,我有组件结构:-AllElements --SingleElement --SingleElementDetails

我将方法See传递给SingleElement组件,我调用seefunc来调用AllElements组件中的see方法。问题我在AllElements中的状态(名称)在第一次onClick触发后没有改变,它在secund点击后发生变化。你能告诉我为什么吗?

    class AllElements extends Component {

        constructor(props) {
            super(props);
            this.state = {
                myData: [],
                viewingElement: {
                    name:""
                }
            }
             this.see = this.see.bind(this);
            console.log('Initial Sate',this.state.viewingElement);
        }


         see(name) {
        this.setState({
          viewingElement: {
            name:name
          }
        });
        console.log('State after SEE',this.state.viewingElement);
      }

        render() {
            const { myData, viewingElement } = this.state;
        return (
          <div>
            {myData.map(se => (
              <SingleElement
                key={se.id}
                name={se.name}
                see={this.see}
              />
            ))}
              <SingleElementDetails viewingElement={viewingElement}/>
          </div>
        );
        }
    }



    class SingleElement extends Component {
    constructor(props) {
        super(props);
    }

    seefunc(name) {
        this.props.see(this.props.name);
        console.log('Name in seefunc props',this.props.name);
    }

    render() {
        return (
            <div onClick={this.seefunc.bind(this)}>
                DIV CONTENT
            </div>
        )
    }
}
javascript reactjs jsx
2个回答
2
投票

你在这里遇到的问题是setState是异步的。它确实是第一次工作,但你没有在你的console.log中看到它,因为console.log发生在状态更新之前。

要查看更新的状态,请使用setState的第二个参数,它是一个回调函数(https://reactjs.org/docs/react-component.html#setstate):

 this.setState({
          viewingElement: {
            name:name
          }
        }, () => {
  console.log('State after SEE',this.state.viewingElement);
});

SingleElement中,使用反应生命周期中的componentWillReceiveProps(nextprops)https://reactjs.org/docs/react-component.html#componentwillreceiveprops)方法来查看更新的道具:

seefunc(name) {
        this.props.see(this.props.name);
    }

componentWillReceiveProps(nextprops) {
        console.log('Name in props',nextProps.name);
}

1
投票

它确实改变了。但是setState是一个异步过程,因此您只需将以前的状态记录到控制台。 setState does provide a callback允许您在异步过程完成后运行代码,因此您可以执行以下操作:

this.setState({
  viewingElement: {
    name:name
  }
}, () => console.log('State after SEE',this.state.viewingElement));

DEMO

© www.soinside.com 2019 - 2024. All rights reserved.