在我的应用程序中,如果用户从登录屏幕登录,我希望导航到仪表板屏幕。我的代码是这样的。
// Login Screen
componentDidUpdate() {
const { auth, history } = this.props;
redirectIfAuthenticated(auth.isAuthenticated, history, './dashboard');
}
static getDerivedStateFromProps = (nextProps, prevState) => {
if (nextProps.errors)
return { errors: nextProps.errors }
return { errors: prevState.errors }
}
// auth util
export const redirectIfAuthenticated = (isAuthenticated, history, screen) => {
if (isAuthenticated) {
history.push(screen);
}
}这与预期的一样。我想知道我做这件事的方式是否正确。我用getDerivedStateFromProps替换了componentWillRecieveProps。现在,我也必须使用componentDidUpdate来实现我使用componentWillRecieveProps时所做的事情。这是正确的吗
发布于 2019-01-31 02:51:48
是的,这就是你应该怎么做。看一看getDerivedStateFromProps's documentation
此外,您可以返回null以避免更新状态,因此我会将prevState.errors部件更改为:
static getDerivedStateFromProps = (nextProps, prevState) => {
if (nextProps.errors) {
return { errors: nextProps.errors }
} else {
return null
}
}https://stackoverflow.com/questions/54447364
复制相似问题