Javascript 如何在React中将componentWillReceiveProps更改/更新为getDerivedStateFromProps?
我知道他们不推荐的组件将接收Props,我被要求用getDerivedStateFromProps替换,但他们似乎根本没有做相同的事情。我也不能。。。访问此或设置设置。我看了这么多关于转换到新方式的文章,但它不适用于我的情况,因为我没有返回对象Javascript 如何在React中将componentWillReceiveProps更改/更新为getDerivedStateFromProps?,javascript,reactjs,Javascript,Reactjs,我知道他们不推荐的组件将接收Props,我被要求用getDerivedStateFromProps替换,但他们似乎根本没有做相同的事情。我也不能。。。访问此或设置设置。我看了这么多关于转换到新方式的文章,但它不适用于我的情况,因为我没有返回对象 static getDerivedStateFromProps(nextProps, prevState) { return nextProps.auth.isAuthenticated ? nextProps.history.p
static getDerivedStateFromProps(nextProps, prevState) {
return nextProps.auth.isAuthenticated
? nextProps.history.push("/dashboard")
: { errors: nextProps.errors };
}
componentWillReceiveProps正在将此路径“/dashboard”推送到this.props.history
getDerivedStateFromProps必须返回一个对象。我该怎么做
componentDidMount() {
// If logged in and user navigates to Login page, should redirect them to dashboard
if (this.props.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
if (nextProps.errors) {
this.setState({
errors: nextProps.errors,
});
}
}
我尝试执行以下操作,但出现一个错误,表示我必须返回一个对象
static getDerivedStateFromProps(nextProps, prevState) {
return nextProps.auth.isAuthenticated
? nextProps.history.push("/dashboard")
: { errors: nextProps.errors };
}
编辑:我使用与原始代码相同的方法尝试ComponentDidUpdate,但结果导致崩溃。
componentDidUpdate(prevProps, prevState) {
if (prevProps.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
if (prevState.errors) {
this.setState({
errors: prevProps.errors,
});
}
}
但这种方式似乎有效。到目前为止没有错误。但我不确定我是否理解上面的代码失败的原因
componentDidUpdate(prevProps) {
console.log(prevProps.auth, this.props.auth, this.props.history);
if (prevProps.auth.isAuthenticated !== this.props.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
console.log(this.props.history);
if (prevProps.errors !== this.props.errors) {
this.setState({
errors: this.props.errors,
});
}
}
问题
在本例中,如果存在任何真实错误状态,则您将持续设置状态,该状态将触发另一个渲染周期,该渲染周期将再次更新状态。。。冲洗和重复,直到崩溃。这就是所谓的无防护状态更新
componentDidUpdate(prevProps, prevState) {
if (prevProps.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
if (prevState.errors) {
this.setState({
errors: prevProps.errors, // <-- sets state and rerenders, repeatedly
});
}
}
您可以在componentdiddupdate()
中立即调用setState()
它必须包装在一个条件中,如上例所示,或者
你将导致一个无限循环
你不能仅仅使用
componentdiddupdate
lifecycle函数并检查this.props.auth.isAuthenticated
来发布导航的副作用?我试过了。我收到以下错误:“错误:超过最大更新深度。当组件在componentWillUpdate或componentDidUpdate中重复调用setState时,可能会发生这种情况。”您是否在其中一个函数中设置无防护状态?也就是说,没有检查prevProps
?我用失败的代码编辑了我的文章。我也发现了一些有用的东西,但我还是很困惑。
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}