【问题标题】:React Native, Fetch, and Dispatch: How do I access responseData within mapDispatchToProps()?React Native、Fetch 和 Dispatch:如何在 mapDispatchToProps() 中访问 responseData?
【发布时间】:2018-02-28 16:52:15
【问题描述】:

我正在从我的“扫描仪”组件中获取 componentWillMount() 中的 JSON 数据,如下所示:

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 中保存的值?

【问题讨论】:

    标签: react-native react-redux fetch dispatch


    【解决方案1】:

    您可以使用 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);
    

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多