我正在从我的“扫描仪”组件中获取 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 中保存的值?
最佳答案
您可以使用 responseData
作为参数调用 action creator 并定义您的 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);
关于react-native - React Native、Fetch 和 Dispatch : How do I access responseData within mapDispatchToProps()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49034706/