我试着学习React,我有一个问题 . 我想从教程中自己做一个例子 .
import React, { Component } from 'react';
class MyComponent extends Component {
state = {
persons: [],
firstPersons: 5,
variables: {
Id: '1',
first: this.firstPersons,
input: {},
}
}
render() {
console.log('this.state', this.state);
return (
<div>
<p>Hello React!!!</p>
</div>
);
}
}
export default MyComponent;
我把渲染方法a console.log(this.state)
.
我的页面中有这个简单的状态,当我运行项目时出现错误:
Uncaught TypeError: Cannot read property 'firstPersons' of undefined
请有人告诉我我的代码有什么问题?
2 回答
我建议你这个语法:
您无法在JS中访问自身内部的对象 . 你应该做:
要么
或者不推荐使用componentWillMount()