这可能是因为异步行动在 Redux 中进行了,但是在执行该操作之前,Axios 已经'解决”了 promise 并返回了 undefined。
一种解决方案是在 Redux 的异步操作中使用 async/await。这样可以在 Axios 请求完成之前等待 Redux 异步操作的完成并发出请求。
例如,使用 Redux-Thunk 中间件,可以这样编写一个 action creator:
import axios from 'axios';
export const fetchData = () => async (dispatch) => {
try {
const response = await axios.get('https://api.example.com/data');
dispatch({ type: 'FETCH_SUCCESS', payload: response.data });
} catch (error) {
dispatch({ type: 'FETCH_ERROR', payload: error.message });
}
};
在其中的 async/await 描述中,我们等待 Axios 的请求完成并从服务器收到数据,然后将其发送到 Redux store 中。
通过使用此类 async action creators,可以确保在 Axios 完成之前不会触发 Redux Reducer 的更新。
下一篇:Axios和数组修改