Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript getDerivedStateFromProps返回未定义_Javascript_Reactjs_Getderivedstatefromprops - Fatal编程技术网

Javascript getDerivedStateFromProps返回未定义

Javascript getDerivedStateFromProps返回未定义,javascript,reactjs,getderivedstatefromprops,Javascript,Reactjs,Getderivedstatefromprops,目前首次使用getDerivedStateFromProps。我的代码可以正常工作,它完成了我希望它完成的任务,但我在控制台中收到了一条警告,这让我很困惑,因为我的代码正在工作。警告:“getDerivedStateFromProps():必须返回有效的状态对象(或null)。您返回的是未定义的。”是否有更好的方法来编写getDerivedStateFromProps,以消除控制台中的警告 static getDerivedStateFromProps(props, state) { stat

目前首次使用getDerivedStateFromProps。我的代码可以正常工作,它完成了我希望它完成的任务,但我在控制台中收到了一条警告,这让我很困惑,因为我的代码正在工作。警告:“getDerivedStateFromProps():必须返回有效的状态对象(或null)。您返回的是未定义的。”是否有更好的方法来编写getDerivedStateFromProps,以消除控制台中的警告

static getDerivedStateFromProps(props, state) {
 state.currentUser.id =
   props.location.state && props.location.state.user
     ? props.location.state.user.id
     : state.currentUser.id;
 state.currentUser.name =
   props.location.state && props.location.state.user
     ? props.location.state.user.name
     : state.currentUser.name;
 state.currentUser.roles =
   props.location.state && props.location.state.user
     ? props.location.state.user.roles
     : state.currentUser.roles;
 state.currentUser.hasAuthenticated = true;
}
该方法应该返回更新后的状态片,而不是更新作为参数传递的状态对象

返回{
当前用户:{
…state.currentUser,
id:props.location.state&&props.location.state.user?props.location.state.user.id:state.currentUser.id,
名称:props.location.state&&props.location.state.user?props.location.state.user.name:state.currentUser.name,
角色:props.location.state&&props.location.state.user?props.location.state.user.roles:state.currentUser.roles,
哈斯:对;
}
}

我添加了
…state.currentUser
,以防您想将
state.currentUser
的一些其他字段保留到新状态。

您很可能不需要使用
getDerivedStateFromProps

似乎您要做的是根据更改的道具更新状态,在这种情况下,
componentdiddupdate()
更合适,但您似乎正在根据传入的道具复制状态

只要在渲染中访问它们就足够了;它们不需要困难的计算。举个假例子:

render() {
  const { userName, id } = this.props.currentUser;
  const hasAuthenticated = id && userName;

  return (hasAuthenticated)
  ?  <WelcomeMessage />
  :  <Login />
}
render(){
const{userName,id}=this.props.currentUser;
const hasAuthenticated=id&&userName;
返回(已验证)
?  
:  
}

state.currentUser.id=
这会改变状态,这在React中是一个很大的禁忌。您应该构造一个新的修改过的状态对象,并在此函数结束时返回它。getDerivedStateFromProps在调用render方法之前被调用,无论是在初始装载还是在后续更新中。它应该返回一个对象来更新状态,或者返回null来不更新任何内容。