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

问题描述 投票:3回答:1

我从我的“扫描仪”组件中获取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个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.