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>
        );
    }
}
我试过四处寻找,但我找不到任何解决我的问题的方法(至少在我有限的理解下我无法理解)。抱歉,如果它很明显,但我才刚刚开始学习React和JSX。
干杯