gpt4 book ai didi

javascript - 如何替换这个组件WillReceiveProps?

转载 作者:行者123 更新时间:2023-11-28 14:11:56 25 4
gpt4 key购买 nike

我有一个登录和注册组件,其中的表单是在这些方法被弃用之前创建的,我一直在四处寻找,但似乎找不到解决方案,我将如何重构它以使用 getDerivedStateFromProps

  componentWillReceiveProps(nextProps) {
if (nextProps.auth.isAuthenticated) {
this.props.history.push("/dashboard")
}

if (nextProps.errors) {
this.setState({
errors: nextProps.errors
});
}

最佳答案

提出的问题的答案可能不会令人满意。 :-) 答案是如果你确实需要从 props ( you probably don't ) 派生状态,只需在 render 中直接使用 props.errors ),您可以使用较新的 getDerivedStateFromProps 来完成此操作接受 props 和状态并(可能)返回要应用的状态更新的 static 方法:

static getDerivedStateFromProps(props, state) {
return props.errors ? {errors: props.errors} : null;
}

或者使用解构并且没有未使用的 state 参数:

static getDerivedStateFromProps(({errors})) {
return errors ? {errors} : null;
}

但是,您是说“但这并不能完成身份验证......?”是的,它没有,因为 componentWillReceiveProps 也不应该有,它违反了规则 props are read-only 。所以那部分不应该存在。相反,如果 props.history 中的该条目应该存在,那么它应该由父组件放置在那里。

关于javascript - 如何替换这个组件WillReceiveProps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com