【发布时间】:2020-10-31 22:26:50
【问题描述】:
在用户更改子组件select 元素的值后,我正在尝试更新父组件的state。
虽然我已经让它有点工作了,但我注意到当我在 select 元素上触发 onChange 事件时,它会返回 previous 值而不是刚刚被选中。
我的反应代码
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。
干杯
【问题讨论】:
-
是控制台看到之前的数据,还是在UI中显示之前的数据?
-
@RohanAgarwal 只是控制台。当我选择新选项时,选择值实际上在 UI 上发生了变化。但这确实意味着我稍后会遇到问题,当 ui 说它正在做一件事时,它实际上正在做另一个后端。
-
这能回答你的问题吗? React setState not Updating Immediately 这个问题每周被问好几次。请在发布问题之前尝试搜索。
标签: javascript reactjs