【问题标题】:Error Retrieving Data from React Redux Store and Mapping to Props从 React Redux 存储中检索数据并映射到道具时出错
【发布时间】:2017-08-24 19:34:54
【问题描述】:

我有一个 React 组件,它通过 API 获取数据,以使用作为组件传入的 ID 来检索产品对象。

我有一个 React / Redux 应用程序,而且我对 Redux 流程还很陌生。 我通过我的 Action / Reducer 将产品(带有一个产品对象的数组)数据加载到商店。

我正在尝试使用 mapStateToProps 模式将其从状态传递到道具。

渲染{ this.props.product.title }时出现以下错误

Uncaught TypeError: Cannot read property '__reactInternalInstance$z9gkwvwuolc' of null

我认为这是因为它是异步的数据。 解决这个问题的最佳方法是什么?

下面是我的代码——

class ProductListItem extends Component {
  componentDidMount() {
    this.props.dispatch(fetchProduct(this.props.id));
  }

  render() {
    return (
      <div>
        <h1>{ this.props.product.title }</h1>
      </div>
    );
  }
}

// Actions required to provide data for this component to render in sever side.
ProductListItem.need = [() => { return fetchProduct(this.props.id); }];

// Retrieve data from store as props
function mapStateToProps(state, props) {
  return {
    product: state.products.data[0],
  };
}

ProductListItem.propTypes = {
  id: PropTypes.string.isRequired,
  dispatch: PropTypes.func.isRequired,
  overlay: PropTypes.string,
};

export default connect(mapStateToProps)(ProductListItem);

【问题讨论】:

    标签: reactjs asynchronous redux redux-store


    【解决方案1】:

    您需要检查产品是否存在,只有存在时您才会访问内部数据。这是一种常见的模式:

    class ProductListItem extends Component {
      componentDidMount() {
        this.props.dispatch(fetchProduct(this.props.id));
      }
    
      render() {
        const { product } = this.props;
        return (
          <div>
            { product &&
              <h1>{product.title}</h1>
            }
          </div>
        );
      }
    }
    

    如果产品存在,那么组件将呈现&lt;h1&gt;

    【讨论】:

    • 啊,这就是我所缺少的!干净的解决方案,谢谢!
    【解决方案2】:

    在你的 redux reducer 中你可以定义默认状态,设置默认状态,然后你可以做一些三元检查

    export default function reducer(state={ title : undefined}, action) {
    
    //ternary checking in render() on component
    product.title !== undefined ? product.title : undefined
    

    这意味着,如果 product.title 不是未定义的,则呈现 product.title 否则未定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 2021-10-19
      • 2020-02-25
      • 1970-01-01
      • 2016-03-07
      • 2019-01-02
      • 2019-04-26
      相关资源
      最近更新 更多