2017-04-08 144 views
0

在React中,我试图使用redux-form执行API更新调用。我可以在initialize的帮助下在编辑表单中获取数据。它运作良好。除非用户刷新浏览器。在这种情况下,我无法获取initialize中的数据,因为它在道具/状态中不可用。Reactjs:在页面刷新时获取/保留REDX格式数据

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..> 
); 

我也尝试作出反应的生命周期方法componentWillMount用于读取数据,但它似乎并没有工作。

当用户刷新浏览器,它会引发错误:

遗漏的类型错误:空

我应该如何解决读取/当用户刷新页面保存的数据无法读取属性“名称”?

回答

0

这不是一个真正的复杂形式的特定问题,它是在单个页面应用程序中维护应用程序状态间刷新的一般问题。 使用redux,您可以存储需要在localStorage中刷新的状态 - 在这种情况下,表单状态。您可以通过创建redux middleware做到这一点“手动”,或有这样的:https://github.com/elgerlambert/redux-localstorage

0

要真正避免Uncaught TypeError: Cannot read property 'name' of null您需要定义defaultProps为你的类/组件。

究竟发生在这里,是因为你的API动作是异步并且需要时间来获取数据时,this.props.user回报undefined这反过来又使this.props.user.nameUncaught 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的状态,你应该使用终极版中间件存储在本地存储或会话存储你的国家的一部分。 更多有关使用中间件从REDX自己的创建者:Building React Applications with Idiomatic Redux

+0

你好,谢谢你的建议。我确实尝试了'defaultProps',但它仍然会抛出相同的错误。 –

相关问题