【问题标题】:Reactjs: Fetch/Preserve redux form data on page refreshReactjs:在页面刷新时获取/保留 redux 表单数据
【发布时间】:2017-04-08 04:07:20
【问题描述】:

在 React 中,我正在尝试使用 redux-form 执行 API 更新调用。在initialize 的帮助下,我可以在编辑表单中获取数据。它运作良好。除非用户刷新浏览器。在这种情况下,我无法在 initialize 中获取数据,因为它在 props/states 中不可用。

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 的属性“名称”

当用户刷新页面时,我应该如何解决获取/保留数据的问题?

【问题讨论】:

    标签: reactjs react-redux redux-form react-redux-form


    【解决方案1】:

    这并不是真正的 redux-form 特定问题,而是在单个页面应用程序中跨刷新维护应用程序状态的一般问题。 使用 redux,您可以在 localStorage 中存储需要通过刷新保持的状态——在这种情况下,是表单状态。您可以通过创建 redux middleware 来“手动”执行此操作,或者是这样的:https://github.com/elgerlambert/redux-localstorage

    【讨论】:

      【解决方案2】:

      要真正避免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 创建者本人的中间件:Building React Applications with Idiomatic Redux

      【讨论】:

      • 您好,谢谢您的建议。我确实尝试过defaultProps,但它仍然抛出同样的错误..
      猜你喜欢
      • 2014-07-24
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多