如何在下拉列表中从数组添加数据?

时间:2019-04-07 21:41:29

标签: javascript arrays reactjs

我正在从API提取数据,并且想在下拉选择中添加该数据。我正在使用ReactJs

class ShowStudents extends React.Component {
  state = {
    nationalities: []
  }

  componentDidMount() {
    this.setNationalities()
  }

  setNationalities = () => {
    fetch('/students/getData')
      .then(response => response.json())
      .then(data => {
        let tempNationalities = data.data.map(product => {
          return { value: product.nationality, display: product.nationality }
        })
        this.setState({ nationalities[...this.state.nationalities, ...tempNationalities ] })
      })
  }

  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-md-4">
            {this.state.nationalities}
          </div>
          <select>
            {this.state.nationalities.map((nationality) => <option key={nationality.value} value={nationality.value}>{nationality.display}</option>)}
          </select>
        </div>
      </div>
    )
  }

}
export default ShowStudents

我需要在state.nationatilites中添加来自tempNationalities的值。当我运行此命令时,出现一个错误:“对象作为React子对象无效(找到:带有键{value,display}的对象)。如果要渲染子代集合,请改为使用数组。”如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

问题:

this.setState({nationalities[...this.state.nationalities,...tempNationalities ] })

应该是:

this.setState({nationalities: [...this.state.nationalities,...tempNationalities ] })

此外,您似乎还在此处渲染对象的原始数组:

<div className="col-md-4">
  {this.state.nationalities}
</div>

您无需使用地图或类似的方法来创建组件,而是在几行之后进行。我认为您看到的错误与上述div有关,该div包含对象数组而不是组件。