首页 > 解决方案 > API调用期间如何在reducer函数中返回状态

问题描述

我有一个 reducer 函数,我必须在其中进行 API 调用,然后将其结果作为状态返回。但是由于 API 调用是异步的,因此 state 的值不会更新。

if (action.type==='CREATE_POST') {
        const x= async () => {
            const res=await  fetch("http://localhost:5000/posts", {
                  method: "post",
                  headers: {
                      'Accept': 'application/json',
                      'Content-Type': 'application/json'
                  },
                  body: JSON.stringify(
                      action.payload
                  )
              })
                  const data= await res.json()
              return data
          }
          return [...state,x]
}

我也试过这个

if (action.type==='CREATE_POST') {
        const x= async () => {
            const res=await  fetch("http://localhost:5000/posts", {
                  method: "post",
                  headers: {
                      'Accept': 'application/json',
                      'Content-Type': 'application/json'
                  },
                  body: JSON.stringify(
                      action.payload
                  )
              })
                  const data= await res.json()
              return data
          }
          return [...state,x().then((data)=>{console.log(data);})]

    }

标签: javascriptreactjsasynchronousasync-awaitfetch

解决方案


如果您正在执行异步任务,我建议您使用以下模式:

创建 3 个文件,命名为:

  1. 减速器.js
  2. 动作.js
  3. effect.js(用于异步任务)

在减速机

const initialState = {
  loading: false,
  data: [],
  error: ''
}

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "FETCH_REQUEST":
      return {
        ...state,
        loading: true
      }
    case "FETCH_SUCCESS":
      return {
        loading: false,
        data: action.payload,
        error: ''
      }
    case "FETCH_FAILURE":
      return {
        loading: false,
        data: [],
        error: action.payload
      }
    default: return state
  }
}

export default reducer

在 action.js 中

export const fetchRequest = () => {
    return {
      type: "FETCH_REQUEST"
    }
  }
  
  export const fetchSuccess = data => {
    return {
      type: "FETCH_SUCCESS",
      payload: data
    }
  }
  
  export const fetchFailure = error => {
    return {
      type: "FETCH_FAILURE",
      payload: error
    }
  }

最后是 effect.js

export const fetch = () => {
    return (dispatch) => {
        //Initializing the request
        dispatch(fetchRequest());
        //Calling the api
        api()
            .then((response) => {
                // response is the data
                dispatch(fetchSuccess(response));
            })
            .catch((error) => {
                // error.message is the error message
                dispatch(fetchFailure(error.message));
            });
    };
};

推荐阅读