我学习了React-Redux,现在我需要有关商店的帮助。当操作FOUND_BAD_WORD
被击中时,无效字词在有效载荷中,我无法正常工作。
我想用以下单词更新Redux Store: (JAVA样式的伪代码)
import { ADD_ARTICLE } from "../constants/action-types";
import { FOUND_BAD_WORD } from "../constants/action-types";
const initialState = {
articles: []
};
var badword;
export default function reducer(state = initialState, action) {
if (action.type === ADD_ARTICLE) {
return Object.assign({}, state, {
articles: state.articles.concat(action.payload)
});
}
if (action.type === FOUND_BAD_WORD) {
// If user type a bad word then save the word in the store
badword = action.payload;
}
return state;
}
我知道这是一个简单的问题,但我已经对此进行搜索,只能找到高级答案
我有一个对象与商店mapStateToProps
上的badword
连接,但无法正常工作,因为我认为我需要先更改无效字词??
答案 0 :(得分:1)
按照您的操作方式,将是:
if (action.type === FOUND_BAD_WORD) {
return Object.assign({}, state, {badword: action.payload})
}
但是在switch语句中处理reducer动作并使用对象传播会更加优雅。
import { ADD_ARTICLE, FOUND_BAD_WORD } from "../constants/action-types";
const initialState = {
articles: [],
};
const yourReducerName = (state = initialState, action) => {
switch(action.type) {
case ADD_ARTICLE : return {
...state,
articles: [...state.articles, action.payload]
}
case FOUND_BAD_WORD : return {
...state,
badword: action.payload
}
default: return {...state}
}
}
export default yourReducerName