我目前正在学习React,我想用WebSockets连接实现动态状态系统。所以我做了一个基本的事件监听系统。这是我的代码:
class UIEvents {
constructor() {
this.Events = {};
}
BindEvent(name, cb) {
if(!this.Events[name]) {
this.Events[name] = [];
}
this.Events[name].push(cb);
}
CallEvent(name, value) {
if(!this.Events[name]) {
return console.error("Event is not registred");
}
for(var cb of this.Events[name]) {
cb(value);
}
}
}
var EventManager = new UIEvents();
class Welcome extends React.Component {
constructor() {
super();
EventManager.BindEvent("name", this.onName)
}
getInitialState = () => {
return {
name: "Haha"
}
}
onName = (name) => {
console.log("Replace??", name)
this.setState({
name: name
})
}
render() {
return <h1>Hello, {this.state.name}</h1>;
}
}
function App() {
return (
<div>
<Welcome />
<Welcome />
<Welcome />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
EventManager.CallEvent("name", "Michel")
但是,我有这个错误
pen.js:54 Uncaught TypeError: Cannot read property 'name' of null
at Welcome.render (pen.js:54)
at p._renderValidatedComponentWithoutOwnerOrContext (react.min.js:13)
at p._renderValidatedComponent (react.min.js:13)
at performInitialMount (react.min.js:13)
at p.mountComponent (react.min.js:13)
at Object.mountComponent (react.min.js:15)
at h.mountChildren (react.min.js:14)
at h._createInitialChildren (react.min.js:13)
at h.mountComponent (react.min.js:13)
at Object.mountComponent (react.min.js:15)
这段代码应该让我不明白错误。
答案 0 :(得分:3)
如果React组件基于ES6类,则应在构造函数中设置初始状态。
constructor() {
super();
EventManager.BindEvent("name", this.onName);
this.state = { name: 'Haha' };
}