通过异步调用了解调度工作

时间:2020-04-25 08:17:39

标签: node.js reactjs react-native async-await

我正在使用Context-Provider和reducers创建一个简单的react native应用。在我的代码中,当我单击屏幕上的登录按钮时,它调用callApi方法,该方法调用后端,还应将token设置为TOKEN NOT LOADED,然后如果API调用返回错误,它将调用reducer中的add_error动作->将token的值设置为TOKEN LOADING ERROR,但是当我在add_error中有断点时,{{ 1}}操作从未设置。我不确定发生了什么。这种编程方式正确吗?

token

================================================ ========================

callApi

const testReducer = (state, action) => {
  switch (action.type) {

   case "callApi":
      api(action.payload.dispatch);
      console.log("callApi action");
      return { ...state, errorMessage: "", token: "TOKEN NOT LOADED" };
    case "add_error":
        console.log("add_error action");
      return { ...state, errorMessage: action.payload, token: "TOKEN LOADING ERROR"  };
    default:
      return state;
  }
};

const callApi = dispatch => async () => {
    dispatch({
        type: "callApi",
        payload: {dispatch}
      })
};

const api = async (dispatch) => {
    try {

      const response = await apiServer.post("/vendor/signin", {
        username : "asdasd",
        password : "asdsd dad",
        "g-recaptcha-response": "asdsd"
      });
      if (response.data.status === "success") {
        console.log("Sign in Success");
      } else {
       console.log("Sign in Error");
       dispatch({
        type: "add_error",
        payload: "Something went wrong with signin"
      });
      }
    } catch (err) {
      dispatch({
        type: "add_error",
        payload: "Something went wrong with signin"
      });
    }
  };

  export const { Provider, Context } = createDataContext(
    testReducer,
    { callApi },
    { errorMessage: "", token: null }
  );

0 个答案:

没有答案