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

我想解析一张Excel工作表,并且在解析之前,我希望后端有一些数据来映射它。

因此,单击“提交”按钮后,我想一个接一个地触发三个操作,并将响应存储在存储区中。我为此使用redux-saga。 在执行三个操作(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调用都发生在工作表被解析之后。 我已经使用saga生成器函数完成了它,并且工作正常。但是我想知道如何使用redux处理这种情况。

cfclx 回答:在onClick函数中调度三个动作,然后使用该响应映射数据是否同步

将api调用(或任何其他异步操作)放入传奇中并不能使该动作同步,它仍然是异步的。另外,redux-saga确实不支持从动作中获取结果-您通过动作触发了一个动作,因此,当动作完成后,它无法将结果返回到最初触发它的代码中。 (您可以尝试通过传递回调以及触发传奇的操作来解决此问题,并让传奇调用回调,但我不推荐这种方法。)

我建议使用传统动作创建者在不使用cars的情况下实现此功能。操作创建者将返回做出异步api调用的promise,并在完成后使用结果进行解析。可能看起来像这样:

redux-saga

您可以让操作创建者分派操作以将数据放入存储区中,而不用结果来解决承诺。但这意味着您必须通过组件的属性来拾取新数据,这可能意味着// 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); }); } 中的内容会检查新属性与旧属性是否不同,如果有,则调用下一个数据获取程序。 IMO认为这种方法更加尴尬。

本文链接:https://www.f2er.com/3164385.html

大家都在问