javascript - getDerivedStateFromProps 返回未定义
问题描述
目前是第一次使用 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;
}
解决方案
该getDerivedStateFromProps
方法应该返回更新后的状态切片,而不是更新作为参数传递的状态对象。
return {
currentUser: {
...state.currentUser,
id: props.location.state && props.location.state.user ? props.location.state.user.id : state.currentUser.id,
name: props.location.state && props.location.state.user ? props.location.state.user.name : state.currentUser.name,
roles: props.location.state && props.location.state.user ? props.location.state.user.roles : state.currentUser.roles,
hasAuthenticated: true;
}
}
我添加了以防您希望将...state.currentUser
其他一些字段保留到新状态中。state.currentUser
推荐阅读
- .htaccess - 需要一个旧网址到新网址
- react-native - 如何使用 expo 和 react-native 将照片从 firebase 存储保存到电话库?
- sql - 在 PG Admin PostgreSQL 中合并 CASE 语句中的相似行
- python - 如何从此列中捕获日期
- java - 如何传递HashMap
从一项活动到另一项活动 - javascript - Jquery无法在选择框中选择选定的选项
- amazon-eks - eks worker 节点如何获取 ecr 登录?
- symfony - 无法在 symfony api-platform 中上传文件
- django - django.db.utils.ProgrammingError:从 SQLite 迁移到 Postgres 后表不存在
- excel - excel中是否有根据显示的数据对值进行分组的功能?