React Native、Fetch 和 Dispatch:如何访问 mapDispatchToProps() 中的 responseData?

React Native, Fetch, and Dispatch: How do I access responseData within mapDispatchToProps()?

我正在从我的 "Scanner" 组件中获取 JSON componentWillMount() 中的数据,如下所示:

async componentWillMount() {
  const url = 'https://foo.com/products/product1.json';

  fetch(url)
  .then((response) => response.json())
  .then((responseData) => this.props.dispatchProductLoad())
  .catch(error => {
    console.log(error);
  });
}

下面是我的发送代码:

function mapDispatchToProps(dispatch) {
  return { dispatchProductLoad: () => dispatch(productLoad(SOMEDATA)) };
};

export default connect(null, mapDispatchToProps)(Scanner);

变量 SOMEDATA 应保存 responseData 的值(目前尚未定义)

所以我的问题是 - 如何将 SOMEDATA 的值设置为 responseData 中保存的值?

您可以使用 responseData 作为参数调用动作创建器,并定义您的 mapDispatchToProps 函数,如

async componentWillMount() {
  const url = 'https://foo.com/products/product1.json';

  fetch(url)
  .then((response) => response.json())
  .then((responseData) => this.props.dispatchProductLoad(responseData))
  .catch(error => {
    console.log(error);
  });
}


function mapDispatchToProps(dispatch) {
  return { dispatchProductLoad: (response) => dispatch(productLoad(response)) };
};

export default connect(null, mapDispatchToProps)(Scanner);