在 React 中,我正在尝试使用 redux-form
执行 API 更新调用。我可以在initialize
的帮助下在编辑表单中获取数据。效果很好。除非用户刷新浏览器。在这种情况下,我无法获取initialize
中的数据,因为它在道具/状态中不可用。
constructor(props){
super(props);
}
componentWillMount(){
this.props.fetchUser(this.props.params.id);
}
render() {
const InitlValues = {
initialValues: {
"name": this.props.user.name,
"city": this.props.user.city
}
}
const { handleSubmit } = this.props;
return(
<form goes here..>
);
我确实尝试了 React 生命周期方法componentWillMount
来获取数据,但它似乎不起作用。
当用户刷新浏览器时,它会引发错误:
未捕获的类型错误: 无法读取 null 的属性"name">
当用户刷新页面时,我应该如何解决获取/保留数据的问题?
这不是一个特定于 redux 表单的问题,而是在单个页面应用程序中跨刷新维护应用程序状态的常见问题。使用 redux,您可以在 localStorage 中存储需要通过刷新来保留的状态 - 在本例中为表单状态。您可以通过创建 redux 中间件来"手动"执行此操作,或者有这个:https://github.com/elgerlambert/redux-localstorage
要真正避免Uncaught TypeError: Cannot read property 'name' of null
,您需要为类/组件定义defaultProps
。
这里究竟发生的情况是,由于您的 API 操作是异步的并且需要时间来获取数据,因此this.props.user
返回undefined
这反过来又会this.props.user.name
抛出Uncaught TypeError
。
尝试这样的事情:
static defaultProps = {
user: { name: '', city: '' }
}
constructor(props){
super(props);
}
componentWillMount(){
this.props.fetchUser(this.props.params.id);
}
render() {
const InitlValues = {
initialValues: {
"name": this.props.user.name,
"city": this.props.user.city
}
}
const { handleSubmit } = this.props;
return(
<form goes here..>
);
PS:如果你真的想持久化你的 redux 状态,你应该使用 Redux 中间件将你的状态部分存储在本地存储或会话存储中。更多关于使用中间件的信息来自 redux 的创建者本人:使用 Habitmatic Redux 构建 React 应用程序