如果用户为某项投票,我正在尝试在通知中设置消息。
这是我遇到的错误,当我单击buttong并唤起我的表决处理程序函数时就会发生。
×
Error: Actions must be plain objects. Use custom middleware for async actions.
这是函数,错误消息突出显示了我称为setNotification函数的行。
const voteHandler = anecdote => {
props.addVote(anecdote);
const notification = `You voted for ${anecdote.content}`;
props.setNotification(notification, 5);
};
这是我的通知减少器:
const initialState = null;
const notificationReducer = (state = initialState, action) => {
switch (action.type) {
case "SET_NOTIFICATION":
state = action.data;
return state;
case "REMOVE_NOTIFICATION":
return initialState;
default:
return state;
}
};
export const setNotification = (content, seconds) => {
return dispatch => {
dispatch({
type: "SET_NOTIFICATION",
content
});
setTimeout(() => {
dispatch({
type: "REMOVE_NOTIFICATION"
});
}, seconds * 1000);
};
};
export const removeNotification = () => {
return dispatch => {
dispatch({
type: "REMOVE_NOTIFICATION",
notification: null
});
};
};
export default notificationReducer;
我一直在尝试此方法,如果我仅将此函数用于setNotification,则将显示通知消息,因此,看来我如何调用setTimeout调用存在问题?
export const setNotification = (content, seconds) => {
return {
type: "SET_NOTIFICATION",
data: content
};
};
我仍在学习Redux,所以也许这是一个明显的错误,但我不确定。谢谢。
答案 0 :(得分:1)
export const setNotification = (content, seconds) => {
return dispatch => {
dispatch({
type: "SET_NOTIFICATION",
content
});
setTimeout(() => {
dispatch({
type: "REMOVE_NOTIFICATION"
});
}, seconds * 1000);
};
};
问题应该来自上面的代码。如果您希望从redux操作中dispatch
多个object
,则需要安装Redux-Thunk。
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// Note: this API requires redux@>=3.1.0
const store = createStore(rootReducer, applyMiddleware(thunk));