不确定的阵列:反应



我只是在尝试运行代码时的React的初学者,我会遇到此错误,请告诉我如何和何处解决错误。任何帮助将不胜感激。

constructor() {
    super();
    this.state = {
        array: [''],
        url:"",
    };
}

search() {
    var path = this.refs.searchbar.value
    this.setState({url: path})
    var newArray = this.state.array;
    newArray.push(path);
    this.setState(array:newArray);
    newArray.map((i)=>{
        console.log(i);
    });
}

错误

Failed to compile.
./src/searchfield.js
  Line 24:  'array' is not defined  no-undef

我想指出的代码有一些问题:

  1. 始终将构造函数的参数传递给超级构造函数。
  2. 由于您在newArray中引用了相同的数组,因此当将url推到它时,实际上是在突变this.state.array。应该避免这种情况;在推动值并更新状态之前先复制数组。
  3. 设置新数组状态时存在语法错误(这引起了您的错误(。

这些东西在下面修复:

constructor(props) {
    super(props);
    this.state = {
        array: [''],
        url: ""
    };
}
search() {
    var path = this.refs.searchbar.value
    this.setState({url: path})
    var newArray = this.state.array.splice();
    newArray.push(path);
    this.setState({array: newArray});
    newArray.map((i)=>{
        console.log(i);
    });
}

最新更新