亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

(React/Redux) Redux 操作中的異步問題

(React/Redux) Redux 操作中的異步問題

開心每一天1111 2022-05-26 10:48:18
無法成功使用過去帖子中的解決方案。每次useEffect在 app.js 上加載應用程序時,我都嘗試運行一個操作,如下所示:  26 | const App = () => {  27 |     28 |   useEffect(() => {> 29 |     store.dispatch(loadUser());  30 |   }, []);  31 |   32 |   return (我得到的錯誤:Error: Actions must be plain objects. Use custom middleware for async actions.那個行動 :export const loadUser = () => (dispatch, getState) => {      dispatch({ type: USER_LOADING})      const token = getState().auth.token      const config = {          headers : {              "Content-type": "application/json"          }      }      if (token) {          config.headers["x-auth=token"] = token      }      axios.get("/api/auth/user", config)       .then(res => dispatch({          type: USER_LOADED,          payload: res.data      }))      .catch(err => {          dispatch(returnErrors(err.response.data, err.response.status))          dispatch({              type: AUTH_ERROR          })      })  }我究竟做錯了什么?
查看完整描述

3 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超21個贊

默認情況下,redux 中的操作必須返回一個帶有type鍵的對象。

您的 redux 操作創建者正在返回一個函數。這是最常與redux-thunk中間件一起使用的模式。如果redux-thunk需要,中間件允許您的操作返回一個函數,該函數接受多次調用的調度方法。

創建 redux 存儲時,您需要安裝該redux-thunk軟件包并將其包含在中間件數組中。


查看完整回答
反對 回復 2022-05-26
?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

Redux 本身就是一個非常簡單的工作流程。調度的動作必須是一個對象,通常帶有一個類型和一個有效負載。對于需要在操作的各個階段進行多次分派的異步操作,此工作流程有些痛苦。這就是Redux Thunk或Redux Sagas等其他工具的用武之地。在我看來,您正在使用 Redux Thunk 但尚未連接 Thunk 中間件。


無論您在哪里創建商店,都需要像這樣應用 redux thunk 中間件。


import { createStore, applyMiddleware } from 'redux';

import thunk from 'redux-thunk';

import rootReducer from './reducers';


// Note: this API requires redux@>=3.1.0

const store = createStore(rootReducer, applyMiddleware(thunk));


查看完整回答
反對 回復 2022-05-26
?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

當您在操作中有異步邏輯時,您必須將某種中間件與 redux 集成,即redux-thunkredux-saga. 我更喜歡 thunk,因為它更易于使用。



查看完整回答
反對 回復 2022-05-26
  • 3 回答
  • 0 關注
  • 278 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號