我有一個React Component
,其中我有一個Form
與多個Select
s。 這些Select
組件的options
作爲props
傳遞給SearchComponent
。如何將值添加到React狀態的數組中
我想選擇的選項存儲在本地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']
};
您是否調試過''handleSelectChange'方法中'v'的值? – Sundeep
它給出一個數組 - 「[」USD「,」GBP「]'。 –
這意味着你正在向現有陣列推送一個數組,看到問題(也許是解決方案?) – Sundeep