在onClick函数中调度三个操作,然后使用该响应映射数据,这是同步的吗



我想解析一个excel表,在解析之前,我想从后端获取一些数据来映射它。

所以在点击Submit按钮后,我想逐个触发三个操作,并将响应存储在商店中。我正在使用redux传奇故事。在三个操作(api调用(之后,我将调用解析函数,并使用从存储中获取的响应进行解析和映射。

我试着一个接一个地调度这三个动作。但一旦它到达网络客户端,即axios实例来调用api,它就会变成异步的,下一行就会被执行。

onSubmit = () => {
/*  I will set the loader on submit button till the api is called and all parsing of excel sheet is done. */
this.setState({
showLoader: true,
}, () => {
this.props.getData1(); //Will be saving it in store as data1
this.props.getData2(); //Will be saving it in store as data2
this.props.getData3(); //Will be saving it in store as data3
/* After this I want to call the parsing function to parse the excel sheet data and map accordingly */
parseExcelData(sheetData); //sheet data is the excel data
}

因此,我预计当我调用"parseExcelData"函数时,存储中的数据,即data1、data2和data3,将在该函数中可用。但是所有的api调用都发生在解析表之后。我已经使用传奇生成器函数完成了它,并且运行良好。但我想知道如何用redux来处理这种情况。

将api调用(或任何其他异步操作(放入saga不会使该操作同步,它仍然是异步的。另外,redux-saga真的不支持从一个动作中获得结果——你用一个动作触发一个saga,所以当saga完成时,它无法将结果返回到最初触发它的代码。)

我建议在没有redux-saga的情况下使用传统的动作创建者来实现这一点。操作创建者将返回进行异步api调用的promise,并在调用完成后解析结果。这可能看起来像这样:

// action creator getData1, getData2, getData3
export const getData1 = () => {
return fetch(apiUrl).then(result => {
return result.json();
}).then(resultJson => {
// also fire an action to put it in the store here
// if other parts of your app need the data
return resultJson;
}).catch(err => {
console.error(err);
});
};
// react component
// assumes 1, 2, and 3 cannot be parallelized
// could also be written with .then instead of await
onSubmit = async () => {
this.setState({showLoader: true}, () => {
const result1 = await this.props.getData1();
const result2 = await this.props.getData2(result1);
const result3 = await this.props.getData3(result2);
});
}

您可以让操作创建者调度一个操作,将数据放入存储中,而不是来解决结果中的承诺。但这意味着您必须通过组件的道具来获取新数据,这可能意味着componentDidUpdate中的某些东西会检查新道具是否与旧道具不同,如果是,则调用下一个数据获取器。国际海事组织的这种做法要尴尬得多。

最新更新