[英]How to change an array item value inside an object passed as state in React?
[英]How to add a value to an array inside a React state
我有一個React Component
,其中有一個帶有多個Select
的Form
。 該options
這些的Select
組件傳遞給SearchComponent
作為props
。
我想將選定的選項存儲在本地state
,並且一旦按下表單的“ Submit
,它就會發送到傳遞作為prop
- searchStatements
函數的父組件。
由於選擇是多個,因此我擁有一個可以選擇並存儲為狀態的所有選項的數組。
class SearchComponent extends Component {
state = {
companies: [],
years: [],
currencies: []
};
render() {
return (
<Form
onSubmit={(e) => {
this.props.searchStatements(this.state.years,
this.state.currencies,this.state.companies);
}}
>
<Select
multiple=true
value={this.state.companies}
options={this.props.companies}
onChange={(e) => this.handleSelectChange('companies', e)}
/>
<Select
multiple=true
value={this.state.years}
options={this.props.years}
onChange={(e) => this.handleSelectChange('years', e)}
/>
<Select
multiple=true
value={this.state.currencies}
options={this.props.currencies}
onChange={(e) => this.handleSelectChange('currencies', e)}
/>
</Form>
);
}
handleSelectChange = (name, v) => {
if (name === 'currencies') {
const newArray = this.state.currencies;
newArray.push(v);
this.setState({'currencies': newArray});
} else if (name === 'companies') {
const newArray = this.state.companies;
newArray.push(v);
this.setState({'currencies': newArray});
} else if (name === 'years') {
const newArray = this.state.years;
newArray.push(v);
this.setState({'years': newArray});
}
};
}
initial state
是這樣的-
state = {
companies: [],
years: [],
currencies: []
};
添加貨幣USD
,它應成為
state = {
companies: [],
years: [],
currencies: ['USD']
};
同樣,添加貨幣GBP
,它應成為
state = {
companies: [],
years: [],
currencies: ['USD', 'GBP']
};
但是,在handleSelectChange()
,添加了幾個選項后,它變成了這樣的東西-
state = {
companies: [['GOOGLE'], ['GOOGLE', 'FACEBOOK']],
years: [],
currencies: [['USD'], ['USD', 'GBP']]
};
如何更改handleSelectChange()
,使最終輸出看起來像這樣-
state = {
companies: ['GOOGLE', 'FACEBOOK'],
years: [],
currencies: ['USD', 'GBP']
};
因為您在“ Select
使用多個值,例如this.state.years
是您選擇的所有年份的數組。 因此,您應該分配選定的值(而不是推/附加)。 所以handleSelectChange
方法應該是
handleSelectChange = (name, v) => {
this.setState({[name]: v});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.