React redux - 将多个项目添加到状态树对象中的数组时出现问题

2 reactjs redux react-redux

我正在查看 redux 并将名称添加到数组中。下面的代码有效(有点!)。

我有几个问题。

  1. 我知道建议每次状态通过减速器时创建一个新的状态树对象,但是我认为即使我更改传入的状态对象它仍然应该工作。在下面的代码中,console.log(store.getState());如果我使用var newArr = state.names.concat(action.name);但是如果我使用则不会state.names.push(action.name);

  2. 如果我添加另一个store.dispatch(action)代码则不起作用。

    store.dispatch({type: 'ADD_NAME',name: 'PhantomTwo'});

谁能解释为什么会这样?

  1. 最后,我需要在 switch 语句之外再次返回状态吗?

这是我目前拥有的代码。

const initialState = {
    names: []
}

function namesApp(state = initialState, action) {
    switch(action.type) {
        case 'ADD_NAME':
            var newArr = state.names.concat(action.name);
            return newArr;
        default: 
            return state;
    }
}

let store = createStore(namesApp);

store.dispatch({
    type: 'ADD_NAME',
    name: 'Phantom'
});

console.log(store.getState()); //returns `["Phantom"]`
Run Code Online (Sandbox Code Playgroud)

Jyo*_*aja 5

array这就是对象可变性的行为

由于React高度关心重新渲染的状态变化,因此我们需要照顾可变性。

下面的代码片段解释了数组的可变性。

let x = [];

let y = x;

console.log(x);
console.log(y);

y.push("First");

console.log(x);
console.log(y);

let z = [...x]; //creating new reference

console.log(z);

x.push("Second");

console.log(x); //updated
console.log(y); //updated
console.log(z); //not updated
Run Code Online (Sandbox Code Playgroud)

因此,为了获得更好的功能,您的减速器将类似于

function namesApp(state = initialState, action) {
    switch(action.type) {
        case 'ADD_NAME':
            return {
                ...state, //optional, necessary if state have other data than names
                ...{
                   names: [...state.names, action.name]
                }
            };
        default: 
            return state;
    }
}
Run Code Online (Sandbox Code Playgroud)