设置数组的状态

时间:2018-06-05 15:36:55

标签: reactjs

我正在尝试通过执行此操作来更新我处于状态的数组

this.state = {
            items: []
        };

我声明如下

items

我在class SubmitButton extends Component { constructor(props) { super(props); this.state = { clicked: false, items: [] }; this.onSubmit = this.onSubmit.bind(this); } onSubmit() { var ddOption = this.props.dropDownOption; var search = this.props.searchTerm.term; var url = "http://localhost:52688/api/WebView/true/" + search; var xhttp = new XMLHttpRequest(); var xhttp.open("GET", url, true); var xhttp.send(); var response = xhttp.responseText.split(','); var data = JSON.parse(response); for (var i = 0; i < data.Ar.length; i++) { this.setState({ items: this.state.items.concat(data.Ar[i]) }); } } render() { if (!this.state.clicked) { return ( <button className="btn btn-primary" onClick={() => this.onSubmit()}>Submit</button> ); } else { return ( <div> <button className="btn btn-primary" onClick={() => this.onSubmit()}>Submit</button> <CardTable items={this.state.items} /> </div> ); } } 中没有得到任何回复,并且在setState之后它的长度仍为零。我对React很新,所以我不确定这里是否有我遗漏的东西。

成分:

{{1}}

}

导出默认提交按钮;

1 个答案:

答案 0 :(得分:4)

你错过了括号。

for (var i = 0; i < data.Ar.length; i++) {    
  this.setState({
        items: this.state.items.concat(data.Ar[i])
    });
}

但这将是一个更好的解决方案:

this.setState({
  items: [...this.state.items, ...data.Ar],
});

它被称为“解构分配”:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

编辑:
尝试使用fetch API而不是旧的XHR。你正在做和异步请求,我猜你设置状态时数据不存在。我还修复了组件中的语法错误。我希望它会起作用,但显然我无法测试它。

class SubmitButton extends Component {
  constructor(props) {
    super(props);
    this.state = {
      clicked: false,
      items: []
    };
    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit() {
    const search = this.props.searchTerm.term;
    fetch(`http://localhost:52688/api/WebView/true/${search}`)
      .then(response => {
        const data = JSON.parse(response);
        this.setState({
          items: [...this.state.items, ...data.Ar],
          clicked: true,
        });
      })
      .catch(err => console.log('Something went wrong', err))
  }

  render() {
    if (!this.state.clicked) {
      return (
        <button className="btn btn-primary" onClick={() => this.onSubmit()}>Submit</button>
      );
    }

    return (
      <div>
        <button className="btn btn-primary" onClick={() => this.onSubmit()}>Submit</button>
        <CardTable items={this.state.items} />
      </div>
    );
  }
}

export default SubmitButton;