gpt4 book ai didi

javascript - Redux-React : How to pass the updated state to function onChange?

转载 作者:行者123 更新时间:2023-12-01 00:06:25 25 4
gpt4 key购买 nike

我是 React 新手,正在尝试一件简单的事情。我不明白如何修改状态并将其传递给函数。请在下面找到我的代码:我跳过了多余的代码,只传递了焦点,除了这个功能之外,一切都正常。

 state = {
card: this.props.card // No probelm here , the props are correctly received in my component
};

我正在尝试更新状态 onChange 并在调度程序中使用此状态值在此事件后生成新状态。请在此处找到此功能的代码片段:

<select
class="form-control m-1"
value={this.state.card.type}
onChange={e => {
let newType = e.target.value;
this.setState(prevState => ({
card: {
...prevState.card,
type: newType
}
}));
console.log(this.state.card) // **This gives me the old state, not updated one**
this.props.updateCard(this.state.card) // Correctly receiving the updateCard Props ,
}}
>
<option value="ABC">Option1</option>
<option value="DEF">Option2</option>
</select>

我的调度员:

updateCard: card=> {
dispatch({ type: "UPDATE_CARD", card: card})}

我的 reducer :

  case "UPDATE_CARD": {
console.log("INSIDE REDUCER");
console.log(action.card);
return {
cards: state.cards.map(card=>
card.id === action.card.id ? action.card: card
)
};
}

请帮忙解决这个问题。我确实在这里搜索了很多东西,但没有任何帮助。

最佳答案

这是因为 setState 不是同步的:

...
onChange ={e => {
let newType = e.target.value;
this.setState(prevState => ({
card: {
...prevState.card,
type: newType
}
}), () => {
console.log(this.state.card) // will give you the new value
// you should also do any updates to redux state here to trigger
// re-renders in the correct sequence and prevent race conditions
});
console.log(this.state.card) // **This gives me the old state, not updated one**
this.props.updateCard(this.state.card) // Correctly receiving the updateCard Props ,
}}
...

关于javascript - Redux-React : How to pass the updated state to function onChange?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60344536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com