簡體   English   中英

Redux-React:如何將更新的狀態傳遞給 onChange 函數?

[英]Redux-React : How to pass the updated state to function onChange?

我是 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})}

我的減速機:

  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 ,
}}
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM