繁体   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