使用redux的正确方法

时间:2017-08-19 16:05:23

标签: javascript reactjs redux axios redux-thunk

我正在使用React,Redux和MongoDB创建小应用程序。 不幸的是,我在使用 axios redux 时遇到了问题。我尝试在里面使用它减少如下:

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;
       }
     .........

但它不起作用。然后我将axios移动到我的动作创建者,所以它看起来像这样:

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));
   }
 }

它将新文档发布到mongo数据库,但它也给我错误:操作必须是普通对象。使用自定义中间件进行异步操作。是的,我正在使用redux thunk;)

有谁能告诉我问题出在哪里?随意请求更多代码,不确定其他什么是有用的。

修改

我正在使用redux-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')
);

1 个答案:

答案 0 :(得分: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')
);