0

我有一个 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);
4

2 回答 2

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

如果产品存在,则组件将呈现<h1>.

于 2017-08-24T19:39:43.543 回答
0

在您的 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 否则未定义。

于 2017-08-24T19:46:43.987 回答