0
私は現在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)
このコードは想定され、このエラーを持っています。
魅力的な作品です。ありがとう – JeePing