反应选择onChange返回以前的值,而不是当前的值 [英] react select onChange returning previous value instead of current

查看:91
本文介绍了反应选择onChange返回以前的值,而不是当前的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to update the state of a parent component after a user changes the value of a child components select element.

虽然我可以使用它,但我注意到当我在 select 元素上触发 onChange 事件时,它将返回 previous值,而不是刚刚选择的值.

While I've got it somewhat working, I've noticed that when I fire the onChange event on my select element it'll return the previous value instead of the one that has just been selected.

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>
        );
    }
}

我尝试四处搜寻,但找不到解决问题的任何解决方案(至少在我有限的理解下我无法理解).道歉很明显,但我才刚刚开始学习 React JSX .

I've tried searching around, but I couldn't find any solutions to my problem (at least none that I could understand with my limited understanding). Apologies if it's glaringly obvious, but I've only just started learning React and JSX.

欢呼

推荐答案

setState 操作本质上是异步的.因此,无论何时完成setState操作,都不能保证状态的更新值仅在 setState 之后可用声明

setState operations are async in nature. So whenever a setState op is done, its not guaranteed that the updated value of state will be available just after the setState statement

从React Doc

From React Doc

React可以将多个setState()调用批处理为一个单独的更新性能.

React may batch multiple setState() calls into a single update for performance.

由于this.props和this.state可能会异步更新,因此您不应依赖于它们的值来计算下一个状态.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

现在,如果要使用新的状态值,则应将值(在这种情况下为 data )存储在变量中,设置状态,但使用该变量执行其他操作函数内部,例如调用API等.

Now, if you want to use the new state value, you should store the value, in this case the data, in a variable, set your state, but use the variable to perform other operation inside the function, like calling API,etc.

编辑(如@Grover所指出):

Edit (As pointed out by @Grover):

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

setState also provides a second argument which is a callback that gets fired after the update operation takes place. One can get the updated state value in it and can use this to perform operations with the updated values.

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

但是,React Doc建议使用componentDidUpdate而不是setState回调.此答案试图解释其原因:什么是相比setState回调,使用componentDidUpdate有什么好处?

However, the React Doc suggests using componentDidUpdate instead of setState callback. This answer tries to explain it why: What is the advantage of using componentDidUpdate over the setState callback?

这篇关于反应选择onChange返回以前的值,而不是当前的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆