第二步操作调用了旧的商店数据

时间:2020-07-14 07:35:58

标签: javascript reactjs redux material-ui

我是Javascript和Reactjs的初学者。单击按钮时,我试图调用多个操作。第一个动作将更新商店数据,第二个动作将已更新的商店数据用于调用api。

当我运行它时,第一个动作运行良好,并且商店正在更新,但是第二个动作正在获取旧的商店数据,而不是更新的数据。 谁能告诉我如何解决这个问题?

我的代码结构大致是这样

import React from 'react';
import {connect} from 'react-redux';
import {changeData,callApiAction} from './actions.js';

const ParentComponent = props => {

    <Button onClick={async () => {
        await props.changeData(props.storeData);    
        await props.callApiAction(props.storedata); 
    }}>
    Click Me!
    </Button>
}

const mapStateToProps = state => {
    return { storeData : state.storeData }
}

export default connect(mapStateToProps, {changeData, callApiAction})(ParentComponent);

actions.js文件就像

export const changeData = (storeData) = async dispatch => {

    // modify Store data

    await dispatch({
        type: UPDATE_STORE,
        payload: {
        newStoreData: storeData
        }       
    })
} 

export const callApiAction = (storeData) = async dispatch => {

    try{
        // call API witht the storeData

    } catch(e) {
        // show Error Dialog
    }
}

1 个答案:

答案 0 :(得分:0)

我对为什么会发生这种情况的唯一解释是因为Redux的数据流方式。 Redux存储同步处理操作,但是您正在使用async / await语法使用它们。我认为这可能与此有关。那么如何解决呢? Redux的文档建议使用中间件。最受欢迎的软件包之一是redux-thunk。 Redux-thunk非常易于使用。

在您的商店中添加以下行:

// ... other imports
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";

const middlewares = [thunk];

// Find your createStore function 
const store = createStore(
  rootReducer, // your root reducer
  compose(applyMiddleware(...middlewares)) // add this line of configuration
);

现在可以在redux中实际使用thunk了:

// Remove the async await syntax from synchronous actions
export const changeData = (storeData) = dispatch => {

    // modify Store data

    dispatch({
        type: UPDATE_STORE,
        payload: {
           newStoreData: storeData
        }       
    })
}


// New action for your api call
export const callApiAction = () => {
  return async (dispatch, getState) => {
    dispatch(changeData());
    const { storeData } = getState().reducerName // Replace with your reducer name where storeData is
    try {
      // call the API
      // Dispatch a success action to update the store or some other logic
   } catch(err) {
      // Here you can dispatch a failure action
   }
};
 

然后,您可以在React组件上直接使用await callApiAction(),而无需使用任何参数,因为它直接从存储中获取参数,而忽略了其他changeData()调用。

编辑:您可以将thunk视为动作创建者或返回其他功能的功能。有关redux-thunk的更多信息:https://github.com/reduxjs/redux-thunk