2017-08-19 65 views
2

我使用React,Redux和MongoDB創建一個小應用程序。 不幸的是,我使用axios還原有問題。我試過用裏面的降低像這樣:正確的方式與redux使用axios

export function users(state = initialState, action) { 
    switch (action.type) { 

    case 'USER_ADD': 
     { 
     axios.post('http://localhost:4200/users/add/post', {user: 
     action.user}).then(() => { 
      return { 
      ...state, 
      items: [ 
       ...state.users, 
       action.user 
      ] 
      } 
     }).catch(err => console.log(err)); 
     break; 
     } 
    ......... 

但它不起作用。然後,我愛可信移動到我的行動創造者,所以它看起來是這樣的:

export function addUser(user) { 

    return function (dispatch) { 
    axios.post('http://localhost:4200/users/add/user', {user:user}) 
     .then(() => dispatch({ 
     type: USER_ADD, 
     user: user 
     })).catch(err => console.log(err)); 
    } 
} 

它發佈新文件蒙戈數據庫,但它也使我的錯誤:操作必須是純對象。使用自定義中間件進行異步操作。是的,我使用的是還原thunk;)

有誰可以告訴我問題在哪裏?隨意要求更多的代碼,不知道還有什麼可用的。

編輯:

我使用的終極版 - 咚這樣的:

import { Provider } from 'react-redux'; 
import { createStore, applyMiddleware } from 'redux'; 
import thunkMiddleware from 'redux-thunk'; 
import reducers from './reducers'; 


const createStoreWithMiddleware = applyMiddleware(thunkMiddleware) 
(createStore); 

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}> 
    <App /> 
    </Provider>, 
    document.getElementById('root') 
); 
+0

您是否已經導入了redux-thunk? – WitVault

+0

是的,我現在編輯我的帖子,以顯示我是如何做到的 – Kreha

+0

備註:減速器應該是純粹的功能,沒有副作用,所以把axios放在那裏真的是個壞主意。 –

回答

1

請嘗試以下代碼。我認爲你沒有正確創建商店。

import { Provider } from 'react-redux'; 
import { createStore,combineReducers, applyMiddleware } from 'redux'; 
import thunkMiddleware from 'redux-thunk'; 
import reducers from './reducers'; 

let reducer = combineReducers(reducers) 
// applyMiddleware supercharges createStore with middleware: 
const createStoreWithMiddleware = createStore(reducer, applyMiddleware(thunkMiddleware)) 
ReactDOM.render(
    <Provider store={createStoreWithMiddleware}> 
    <App /> 
    </Provider>, 
    document.getElementById('root') 
); 
+0

我已經使用了combineReducers。那些從'./reducers'導入的reducer是reducer合併爲一。我需要再次合併嗎? – Kreha

+0

@ kreha不,你不需要那麼。 – WitVault

+0

仍然有這個錯誤 – Kreha