javascript - 如何替换这个组件WillReceiveProps?
问题描述
我有一个登录和注册组件,其中包含在不推荐使用这些方法之前不久创建的表单,我一直在环顾四周,但似乎找不到解决方案,我将如何将其重构为使用getDerivedStateFromProps
?
componentWillReceiveProps(nextProps) {
if (nextProps.auth.isAuthenticated) {
this.props.history.push("/dashboard")
}
if (nextProps.errors) {
this.setState({
errors: nextProps.errors
});
}
解决方案
由于您componentWillReceiveProps
用于与本地状态保持同步,props
因此有两种选择:
根据 props 声明你的初始状态并使用componentDidUpdate
来保证 props 的同步性
class Component extends React.Component{
state = { foo : this.props.foo }
componentDidUpdate(prevProps){
if(this.props.foo !== prevProps.foo)
this.setState({ foo : prevProps.foo })
}
}
这实际上每次都会触发额外的渲染,如果您有一些始终等于某个道具的本地状态,则可以直接使用该道具。
用于getDerivedStateFromProps
根据道具更改更新状态,但请记住,您可能不需要使用它
class Component extends React.Component{
static getDerivedStateFromProps(props){
return { foo : props.foo }
}
}
推荐阅读
- android - 如何在 github 工作流中缓存 JDK 和 android sdk?
- javascript - 正则表达式替换字符串的中间字符
- macos-mojave - 为什么在我的 Mac 上安装的版本是 10.15.5 的 xCode 中看到 macOS 11.1?
- codeigniter-3 - 使用 required 和回调函数使用验证表单时出错
- azure - 我需要在使用 PowerShell 创建 Azure VMSS 时指定操作系统磁盘名称
- accelerometer - 如何将原始加速度计数据转换为有关重复运动的信息
- ios - 如何使用我从情节提要添加的页面控件?迅速
- python - 我们可以在异步函数中使用 Flask test_client()
- python - Python 数据框总结
- java - 如何将其从 Scanner 更改为 BufferedReader?