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

标签 javascript reactjs web redux react-redux

我是 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/

相关文章:

javascript - 当有一组 div 时使用 fadeToggle + 淡出所有其他内容

javascript - React HOC 返回一个匿名 _class

javascript - JS 正则表达式 url 验证

php - 控制自己的浏览器的脚本

javascript - 如何在Draft.js中使用策略函数Decorator?

javascript - 未捕获的类型错误 : Cannot read property 'querySelector' of null when using with html

javascript - iFrame 只能显示源代码吗?

javascript - 如何生成一个新的 Angular 4 项目而不是创建生成 Angular 6?

javascript - 如何在 JavaScript 中按顺序运行函数?

javascript - 按钮 onClick 目标正在更改