我只是在尝试运行代码时的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
我想指出的代码有一些问题:
- 始终将构造函数的参数传递给超级构造函数。
- 由于您在
newArray
中引用了相同的数组,因此当将url
推到它时,实际上是在突变this.state.array
。应该避免这种情况;在推动值并更新状态之前先复制数组。 - 设置新数组状态时存在语法错误(这引起了您的错误(。
这些东西在下面修复:
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);
});
}