我'm creating little app using React, Redux and MongoDB. Unfortunately I'在使用 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;)
谁能告诉我问题出在哪里?随意请求更多代码,不确定其他什么是有用的 .
EDIT:
我正在使用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 回答
请尝试下面的代码 . 我认为你没有正确创建商店 .