[英]ReactJs: How to make root component rerender when a prop changes
我有这个管理通知的组件NotificationToast
。
当用户通过身份验证时,我需要始终呈现。
所以这就是我所做的:
class App extends Component {
render() {
const state = store.getState();
const { isAuthenticated } = state.auth;
return (
<Provider store={store}>
<BrowserRouter basename="/">
<Switch>
<PublicRoute path="/register-page" component={RegisterPage} />
<PrivateRoute path="/profile-page" component={ProfilePage} />
<Redirect to="/home" />
</Switch>
{isAuthenticated && (
<div>
<NotificationToast />
</div>
)}
</BrowserRouter>
</Provider>
);
}
}
export default App;
问题是这在以下情况下不起作用:
state.auth.isAuthenticated
是false
的state.auth.isAuthenticated
设置为true
。App
没有检测到这种变化,所以它没有被重新渲染。NotificationToast
不会被渲染。 这在用户登录后刷新页面时有效,因为state.auth.isAuthenticated
从一开始就是true
。
这是因为这段代码:
if (localStorage.jwtToken) {
// Set auth token header auth
setAuthToken(localStorage.jwtToken);
// Decode token and get user info and expiration
const decoded = jwt_decode(localStorage.jwtToken);
// Set User and is Authenticated
store.dispatch(setCurrentUser(decoded));
// Now if you reload a page, if the user has already logged-in you will still have his info in he state
store.dispatch(clearCurrentProfile());
// Check for expired token
const currentTime = Date.now() / 1000;
if (decoded.exp < currentTime) {
store.dispatch(logoutUser());
store.dispatch(clearCurrentProfile());
// Redirect to login
window.location.href = "/login";
}
}
它检查用户是否已经登录,如果他已经登录,则将state.auth.isAuthenticated
设置为true
。
有什么建议么?
useStore 用于检索存储。 但是这种存储访问只能用于存储操作,例如reducer替换。 当 store 改变时,以这种方式访问 store 的组件不会更新。
请使用“useSelector”
const isAuthenticated = useSelector(state => state.auth)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.