![](/img/trans.png)
[英]Is this the correct way to update a state based on the previous state in react?
[英]Correct way to update state with react select multiple
我為我的應用添加了 react-select package。 我想使用CreatableMulti
組件在 select 選項中創建新值,並將新創建的值推送到我的 state 數組中。
我遇到的問題是第一個類型的元素沒有被推入 state 數組。 第二次推送到 state。 第三次第一個元素被推送兩次。
我在代碼盒中創建了代碼副本: https://codesandbox.io/s/react-codesandboxer-example-el0ps?file=/example.js:164-178
以及如何將X
符號與 state 連接以從數組中刪除元素。 如果我單擊X
,整個數組的副本將被推入數組。
用於提高性能的 React 有時會批處理 this.setState() 調用,而不是一次執行一個調用,這可能會導致意外行為。 通過 map 操作數據后,嘗試將 newValues 合並到 state。
像這樣的東西:
const newValuesArr = newValue.map(item => item.value);
this.setState({ values: newValuesArr });
更深入的解釋請參考這個鏈接: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
請運行以下代碼,如果它解決了您的問題,請告訴我。
import React, { Component } from "react";
import CreatableSelect from "react-select/creatable";
import { colourOptions } from "./docs/data";
export default class CreatableMulti extends Component<*, State> {
state = {
values: []
};
handleChange = (newValue: any, actionMeta: any) => {
const newValuesArr = newValue ? newValue.map(item => item.value) : [];
this.setState({ values: newValuesArr });
};
render() {
return (
<CreatableSelect
isMulti
onChange={this.handleChange}
options={colourOptions}
/>
);
}
}
根據文檔
setState()
並不總是立即更新組件。 它可能會批量更新或將更新推遲到以后。 這使得在調用setState()
之后立即閱讀this.state
是一個潛在的陷阱。 相反,請使用componentDidUpdate
或setState
回調 (setState(updater, callback)
),它們都保證在應用更新后觸發。 如果您需要在之前的 state 的基礎上設置 state,請閱讀下面的updater
參數。
所以你可以在你的情況下實現你想要的,如下所示
import React, { Component } from "react";
import CreatableSelect from "react-select/creatable";
import { colourOptions } from "./docs/data";
export default class CreatableMulti extends Component<*, State> {
state = {
values: []
};
handleChange = (newValue: any, actionMeta: any) => {
const newValuesArr = newValue ? newValue.map(item => item.value) : [];
this.setState({ values: newValuesArr }, () => {
console.log(this.state.values);
});
};
render() {
return (
<CreatableSelect
isMulti
onChange={this.handleChange}
options={colourOptions}
/>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.