react select onChange 返回以前的值而不是当前值

IT技术 javascript reactjs
2021-04-03 22:33:58

state在用户更改子组件select元素的值后,我试图更新父组件的

虽然我已经让它有些工作,但我注意到当我onChange在我的select元素触发事件时,它会返回以前的值而不是刚刚选择的值。

我的react代码

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            data: {
                condition: "any"
            }
        };
    }

    update = data => {
        this.setState({ data: { ...this.state.data, ...data } });
        // this gets called every time i change the value of my select
        console.log(this.state.data);
    }

    render(){
        return (
            <div className="parent">
                <Child
                    condition={ this.state.data.condition } 
                    onUpdate={ data => this.update(data) } />
            </div>
        );
    }
}

class Child extends React.Component{
    updateParent = data => {
        this.props.onUpdate(data);
    }

    condition = props => {
        const options = [["any", "Any Condition"], ["new", "Brand New"], ["used", "Used"]];
        return (
            <select 
                defaultValue={ props.selected } 
                // if i select 'used', the console will return 'any', 
                // then if i select 'new', the console will return 'used'
                onChange={({ target }) => this.updateParent({ condition: target.value })}>
                {
                    options.map(([id, name]) => <option key={id} value={id}>{name}</option>)
                }
            </select>
        );
    }

    render(){
        return (
            <div className="child">
                <this.condition selected={ this.props.condition } />
            </div>
        );
    }
}

我试过四处寻找,但我找不到任何解决我的问题的方法(至少在我有限的理解下我无法理解)。抱歉,如果它很明显,但我才刚刚开始学习ReactJSX

干杯

1个回答

setState操作本质上是异步的。因此,无论何时完成 setState 操作,都不能保证 state 的更新值将在setState 语句之后立即可用

来自 React 文档

React 可以将多个 setState() 调用批处理为单个更新以提高性能。

因为 this.props 和 this.state 可能会异步更新,所以你不应该依赖它们的值来计算下一个状态。

现在,如果你想使用新的状态值,你应该存储值,在这种情况下data,在一个变量中,设置你的状态,但使用该变量在函数内部执行其他操作,如调用 API 等。

编辑(正如@Grover 指出的那样):

setState还提供了第二个参数,它是在更新操作发生后触发的回调。可以在其中获取更新的状态值,并可以使用它来对更新的值执行操作。

this.setState({foo: 'bar'}, () => { 
    // actions
});

然而,React Doc 建议使用 componentDidUpdate 而不是 setState 回调。这个答案试图解释为什么:使用 componentDidUpdate 比 setState 回调有什么优势?