如何使用JavaScript数组进行反应选择选项

时间:2018-07-08 17:10:01

标签: javascript reactjs select

我想将Java脚本数组作为选项传递给JSX中的react-select,但这会抛出一个

  

TypeError:options.filter不是函数

我的代码是

  constructor(props) {
    super(props);
    this.state = {
      selectedOption: '',
      optionArray: {}
    }
    this.publishedMsgSet = [];
    this.handleChange = this.handleChange.bind(this);
    this.handleDataReceived = this.handleDataReceived.bind(this);
  }

  handleDataReceived(data) {
    this.state.optionArray = [
      { value: 'suggestion', label: 'suggestion' },
      { value: 'abcabc', label: 'abcdabc' },
    ];
    console.log(JSON.stringify(this.state.optionArray));

  }

  render() {
    return (
      <Select
        styles={this.props.muiTheme.name === 'dark' ? customStyles : {}}
        name="form-field-name"
        value={this.state.selectedOption}
        onChange={this.handleChange}
        options={this.state.optionArray} <-- is this a valid statement
      />

    );
  }

如何将optionArray值作为选项传递给select标签?

1 个答案:

答案 0 :(得分:1)

您将optionArray的初始值定义为 Object ,而不是数组:

this.state = {
  selectedOption: '',
  optionArray: {} // This in an object
}

必须是:

this.state = {
  selectedOption: '',
  optionArray: [] // Empty array
}

而且,这是错误的:

handleDataReceived(data) {
    this.state.optionArray = [
      { value: 'suggestion', label: 'suggestion' },
      { value: 'abcabc', label: 'abcdabc' },
    ];

}

您不应直接更改状态,而应调用 setState()

handleDataReceived(data) {
  this.setState({
    optionArray: data // Expecting "data" is an array
  });      
}

要传递道具,可以:

options={this.state.optionArray} 

它将通过一个名为optionArray的道具。 Select应该期望有一个数组,因为正在尝试调用filter。