我的 react 应用程序作为路由,如下所示:
<Route handler={RouteHandler}>
<Route name="welcome" path="welcome" handler={WelcomePage} />
<Route name="app" path="/" handler={Application}>
<Route name="some-page" path="some-page" handler={SomePage} />
</Route>
</Route>
主要的“应用程序”布局如下
export default class Application extends React.Component {
render() {
return (<div>
<ModalView />
<TopBar />
<RouteHandler />
</div>);
}
}
给我带来问题的 TopBar:
export default class TopBar extends React.Component {
componentDidMount() {
userStore.addChangeListener(this._onChange);
}
componentWillUnmount() {
userStore.removeChangeListener(this._onChange);
}
_onChange = () => {
this.setState(this.getState());
};
handleLoginClick() {
actions.queueModal("login");
}
handleSignupClick() {
actions.queueModal("signup");
}
getState() {
return {
currentUser: userStore.currentUser
};
}
state = this.getState();
render() {
return (
<div className="topBar">
{this.state.currentUser ?
(<Link to="home"><button className="default">{this.state.currentUser.email}</button></Link>) :
([
<button key={1} className="clear" onClick={this.handleSignupClick}>Sign up</button>,
<button key={2} className="clear" onClick={this.handleLoginClick}>Log in</button>
])}
</div>
);
}
}
根据“App”布局,当我在某个页面时,应该安装TopBar。 现在,当我完成登录时,userStore 会发出一个更改,该更改由 TopBar 接收。我收到一条错误消息,而不是栏自行更新,而是“警告:setState(...):只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了 setState()。这是一个 no-操作。”这是为什么?
最佳答案
看起来您没有组件 TopBar 的初始状态。尝试在构造函数中设置初始状态。
constructor(props) {
super(props);
this.state = {name: props.name};
}
关于javascript - react 组件已卸载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32193938/