ReactJS:为什么将值推入 this.state 数组会导致类型错误? [英] ReactJS: why is pushing value into this.state array causing type error?
问题描述
我试图将一个值推送到状态数组中,但出现问题 TypeError: Cannot read property 'state' of undefined at this.state.rows.push(a);
知道为什么吗?单击按钮后,我试图将新值推送到数组中.
App.js
import React, { Component } from 'react';从'./logo.svg'导入标志;导入'./App.css';类 App 扩展组件 {构造函数(){极好的();this.state = {名称: '',行:['你好',<p>gfdfg</p>,'mello']}}句柄(e){e.preventDefault();var a = "h";this.state.rows.push(a);警报(你好");}使成为() {返回 (<div className="应用程序">按钮<br/><input type="submit" id="black" onClick={this.handle}/><br/><p>{this.state.rows}</p>
);}}导出默认应用程序;
这里有几个错误:
- 你永远不应该直接改变状态:
这是一个很大的不:
this.state.rows.push(a);
相反,您应该执行以下操作:<代码>this.setState({ 行 : [...this.state.rows, a] })
或没有 ES6:
const newArray = this.state.rows.slice();newArray.push(a);this.setState({ rows: newArray })
你应该总是用新的状态替换状态.
this
在 React 组件中并不是你想象的那样,为了让它工作,你可以做两件事之一:
一个.将您的方法更改为箭头函数:
handle = (e) =>{e.preventDefault();var a = "h";this.state.rows.push(a);警报(你好");}
B.将 this
绑定到方法:
constructor() {极好的();this.state = {名称: '',行:['你好',<p>gfdfg</p>,'mello']}this.handle = this.handle.bind(this);}
I tried to push a value into a state array but I get an issue TypeError: Cannot read property 'state' of undefined at this.state.rows.push(a);
Know why? I am trying to push a new value into the array after i click a button.
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
name: '',
rows: ['hello',<p>gfdfg</p>,'mello']
}
}
handle(e){
e.preventDefault();
var a = "h";
this.state.rows.push(a);
alert("hello");
}
render() {
return (
<div className="App">
Button<br/>
<input type="submit" id="black" onClick={this.handle}/><br/>
<p>{this.state.rows}</p>
</div>
);
}
}
export default App;
There are couple of things that are wrong here:
- you should NEVER change the state directly:
This is a big No No:
this.state.rows.push(a);
instead you should do something like this:
this.setState({ rows : [...this.state.rows, a] })
or without ES6:
const newArray = this.state.rows.slice();
newArray.push(a);
this.setState({ rows: newArray })
You should always replace the state with a new one.
this
in a react component is not what you think it is, in order to make it work you can do one of two things:
a. change your method to an arrow function:
handle = (e) => {
e.preventDefault();
var a = "h";
this.state.rows.push(a);
alert("hello");
}
b. bind this
to the method:
constructor() {
super();
this.state = {
name: '',
rows: ['hello',<p>gfdfg</p>,'mello']
}
this.handle = this.handle.bind(this);
}
这篇关于ReactJS:为什么将值推入 this.state 数组会导致类型错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!