【发布时间】:2017-07-12 08:42:35
【问题描述】:
我正在将一个属性从我的“根”传递给我的反应路线“家”。
当我的应用程序的“状态”(state.loggedIn)发生变化时,“主页”会更新(外观按预期更改)但不会调用“shouldComponentUpdate”。
我想使用“shouldComponentUpdate”来检测根中的属性(“loggedIn”)是否发生了变化,并做一些额外的工作。
// Root.js
import {Provider} from 'react-redux';
import {
BrowserRouter as Router,
Redirect,
Route,
Switch} from 'react-router-dom';
...
render() {
const store = this.props.store;
const loggedIn = this.state.loggedIn;
const handleLogin = this.handleLogin;
const handleLogout = this.handleLogout;
return (
<Provider store={store}>
<Router history={browserHistory}>
<Switch>
<Route exact path="/" component={
(props) => (
<Home
history={props.history}
loggedIn={loggedIn}
handleLogout={handleLogout}/>)} />
<Route path="/login" component={
(props) => (
<Login
history={props.history}
handleLogin={handleLogin}/>)} />
<Route path="/workflow" component={
loggedIn ?
((props) => (
<Workflows
history={props.history}
match={props.match}/>)) :
((props) => (
<Redirect to={
{
pathname: '/',
state: {from: props.location},
}
}/>)) }/>
</Switch>
</Router>
</Provider>
);
}
// Home.js
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps);
console.log(nextState);
if(nextProps.loggedIn !== nextState.loggedIn) {
if(nextState.loggedIn) {
this.socket.connect();
} else {
this.socket.disconnect();
}
}
return true;
}
【问题讨论】:
-
是否有可能每次都重新安装组件而不是重新渲染?这可能解释了为什么组件被重绘,但生命周期方法没有被调用。如果您在
componentWillMount()中粘贴一条日志语句,您将能够查看它是否被多次调用。 -
尝试将
component更改为render -
@MattWatson 观察构造函数或 componentWillMount 工作 - 请提交答案让我接受!
-
@Skribja 运气不好
标签: reactjs react-redux react-router-v4