你不能有
this.state.chan.on(...)
在类体之外的函数。不过,您可以将所有这些代码放在构造函数中。此外,您的
setState
class HelloWorld extends React.Component {
constructor(props) {
super();
this.state = {
chan: props.channel,
mess: props.message
};
this.state.chan.on("new_message", payload => {
this.setState({mess: payload.body});
});
}
...
}
不过,这有一个问题。这个
on
即使该组件从DOM中卸载,回调也会一直被触发。您应该在中订阅邮件
componentDidMount
componentWillUnmount
:
class HelloWorld extends React.Component {
constructor(props) {
super();
this.state = {
chan: props.channel,
mess: props.message
};
}
componentDidMount() {
const ref = this.state.chan.on("new_message", payload => {
this.setState({mess: payload.body});
});
this.setState({ref: ref});
}
componentWillUnmount() {
this.state.chan.off("new_message", this.state.ref);
}
...
}