state在react redux中得到不同的值



标题可能有误导性,但情况如下:
reducer.js:

// initial state
const initialState = {
notes: [
{
content: "reducer defines how redux store works",
important: true,
id: 1,
},
{
content: "state of store can contain any data",
important: false,
id: 2,
},
],
filter: "IMPORTANT",
};
// reducer
const noteReducer = (state = initialState, action) => {
switch (action.type) {
case "NEW_NOTE":
console.log("state", state);
return state.notes.concat(action.data); 
// ...
}
const generateId = () => Math.floor(Math.random() * 1000000);
// action
export const createNote = (content) => {
return {
type: "NEW_NOTE",
data: {
content,
important: false,
id: generateId(),
},
};
};

在index.js:中

const reducer = combineReducers({
notes: noteReducer,
filter: filterReducer,
});
const store = createStore(reducer, composeWithDevTools());
//dispatch a note from index.js
//it works here
store.dispatch(
createNote("combineReducers forms one reducer from many simple reducers")
);

在reducer.js:中的console.log("state", state);中返回

state 
{notes: Array(2), filter: 'IMPORTANT'}
filter: "IMPORTANT" // 'filter' is here
notes: (2) [{…}, {…}]
[[Prototype]]: Object //prototype is object

这里createNote是成功的
但是,当通过创建新纸币时

const NewNote = (props) => {
const dispatch = useDispatch();
const addNote = (event) => {
event.preventDefault();
const content = event.target.note.value;
event.target.note.value = "";
// createNote does not work here
dispatch(createNote(content));
};
return (
<form onSubmit={addNote}>
<input name="note" />
<button type="submit">add</button>
</form>
);
};

此处console.log("state", state);返回:

state 
(3) [{…}, {…}, {…}]
0: {content: 'reducer defines how redux store works', important: true, id: 1}
1: {content: 'state of store can contain any data', important: false, id: 2}
2: {content: 'combineReducers forms one reducer from many simple reducers', important: false, id: 824517}
length: 3
// 'filter' is missing
[[Prototype]]: Array(0) // state prototype changed to array

其中filter已离开状态,因此创建不成功
简而言之,store.dispatch( createNote("...") );有效,但dispatch(createNote(content));无效
原因似乎是noteReducer接收到不同的状态。但在这两种情况下都没有指定filter
我想知道为什么会发生这种情况,以及如何解决?

正如我们所知,当您使用reducer时,reducer需要两个参数,一个用于初始统计,另一个用于操作。任何操作都将在reducer中运行,您需要通过使用的排列运算符{…state}保存旧状态

case";NEW_NOTE":console.log("state",state(;{…state,notes:state.notes.concat(action.data(}

发现问题
noteReducer应为:

const noteReducer = (state = initialState, action) => {
switch (action.type) {
case "NEW_NOTE":
return { ...state, notes: state.notes.concat(action.data) };
//...
}

刚刚发现上面是一个错误的修复。正确的是:

const noteReducer = (state = initialState.notes, action) => {

否则CCD_ 10也在改变滤波器。但它应该只是改变CCD_ 11部分。

相关内容

  • 没有找到相关文章

最新更新