为什么不使用 Object.assign 的减速器更新状态?
Why isn't state being updated with a reducer using Object.assign?
我正在尝试创建一个没有 ES6 优势的减速器。这是一个旧的 PHP 应用程序,没有用于转换的构建过程。
我正在初始化状态:
let defaultState = {
accountTypes: {
personal: {
selected: false,
checking: {
selected: false
},
savings: {
selected: false
}
},
business: {
selected: false,
checking: {
selected: false
},
savings: {
selected: false
}
}
}
};
这是减速器,然后是存储初始化:
function reducer(state, action) {
switch (action.type) {
case 'TOGGLE_ACCOUNT_TYPE':
console.log(state.accountTypes);
// {
// business: {selected: false, checking: {…}, savings: {…}}
// personal: {selected: true}
// }
console.log(action.payload);
// {
// personal: {selected: true}
// }
let blah = Object.assign({}, state, {
accountTypes: Object.assign({}, state.accountTypes, action.payload)
});
console.log(blah.accountTypes);
// {
// business: {selected: false, checking: {…}, savings: {…}}
// personal: {selected: true}
// }
return blah;
default:
return state;
}
}
const store = Redux.createStore(reducer, defaultState);
let state = store.getState();
稍后订阅状态,在 jQuery 的 document.ready
:
中
store.subscribe(function () {
console.log(state.accountTypes);
// {
// business: {selected: false, checking: {…}, savings: {…}}
// personal: {selected: false, checking: {…}, savings: {…}}
// }
您可以看到状态未使用操作负载更新。
我想我只是偶然发现了我的答案。发布问题会引起一些松动。我在 jQuery 操作中使用了一个陈旧的状态变量。
store.subscribe(function () {
// update the state var
state = store.getState();
如果有更好的方法来使用状态变量而无需手动刷新它,请post另一个答案。
我正在尝试创建一个没有 ES6 优势的减速器。这是一个旧的 PHP 应用程序,没有用于转换的构建过程。
我正在初始化状态:
let defaultState = {
accountTypes: {
personal: {
selected: false,
checking: {
selected: false
},
savings: {
selected: false
}
},
business: {
selected: false,
checking: {
selected: false
},
savings: {
selected: false
}
}
}
};
这是减速器,然后是存储初始化:
function reducer(state, action) {
switch (action.type) {
case 'TOGGLE_ACCOUNT_TYPE':
console.log(state.accountTypes);
// {
// business: {selected: false, checking: {…}, savings: {…}}
// personal: {selected: true}
// }
console.log(action.payload);
// {
// personal: {selected: true}
// }
let blah = Object.assign({}, state, {
accountTypes: Object.assign({}, state.accountTypes, action.payload)
});
console.log(blah.accountTypes);
// {
// business: {selected: false, checking: {…}, savings: {…}}
// personal: {selected: true}
// }
return blah;
default:
return state;
}
}
const store = Redux.createStore(reducer, defaultState);
let state = store.getState();
稍后订阅状态,在 jQuery 的 document.ready
:
store.subscribe(function () {
console.log(state.accountTypes);
// {
// business: {selected: false, checking: {…}, savings: {…}}
// personal: {selected: false, checking: {…}, savings: {…}}
// }
您可以看到状态未使用操作负载更新。
我想我只是偶然发现了我的答案。发布问题会引起一些松动。我在 jQuery 操作中使用了一个陈旧的状态变量。
store.subscribe(function () {
// update the state var
state = store.getState();
如果有更好的方法来使用状态变量而无需手动刷新它,请post另一个答案。