Javascript 如何在react js中接收更新的道具?
您能告诉我如何在react js中接收更新的道具吗?我知道Javascript 如何在react js中接收更新的道具?,javascript,reactjs,redux,Javascript,Reactjs,Redux,您能告诉我如何在react js中接收更新的道具吗?我知道组件将接收道具是不安全的,我尝试使用getDerivedStateFromProps但不起作用 这是我的密码 两秒钟后,我正在更新我的状态,该状态将传递到props 两秒钟后的预期输出 abcsssss static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.src !== "") { return { src: nextProps.
组件将接收道具
是不安全的
,我尝试使用getDerivedStateFromProps
但不起作用
这是我的密码
两秒钟后,我正在更新我的状态,该状态将传递到props
两秒钟后的预期输出
abcsssss
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.src !== "") {
return { src: nextProps.src };
} else return null;
}
您可以使用
componentdiddupdate
componentDidUpdate()在更新发生后立即调用
类Hello扩展组件{
状态={
姓名:“
}
componentDidUpdate(prevProps){
if(this.props.src!==prevProps.src){
this.setState({name:this.props.src+'ssss'});
}
}
render(){
返回{this.state.name};
}
}
您应该使用componentDidUpdate(prevProps,prevState)
只要组件处于接收新道具或内部状态,就会调用componentDidUpdate。在这里,您可以在重新提交组件之前进行干预
因此,在hello.js中,不是getDerivedState:
componentDidUpdate(prevProps) {
if (prevProps.src !== this.props.src) {
this.test()
}
}
比较“if(prevProps.src!==this.props.src)”完成,因此组件仅在src属性更改时更新,防止不必要的重新渲染。您正在设置
this.state.src
,但渲染方法使用this.state.name
。当安装组件时,您确实调用了this.test()
,但之后就再也不会调用了。正确`但我想调用一个函数test
。这样,当收到新道具时,它将给出预期的输出abcsss
如何调用test
函数
componentDidUpdate(prevProps) {
if (prevProps.src !== this.props.src) {
this.test()
}
}