簡體   English   中英

如何在React狀態內向數組添加值

[英]How to add a value to an array inside a React state

我有一個React Component ,其中有一個帶有多個SelectForm 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.

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