【发布时间】:2020-07-05 16:24:22
【问题描述】:
我对 Reactjs 和 Redux 非常陌生,任何人都可以解释什么是 reactjs/redux 中的 Mutable 和 Immutable?
我正在使用 Redux 更新状态,并使用它来控制我的 UI 布局,但我发现下面的方法之一不起作用,尽管两者也在更新对象。
我有一个商店对象,如下所示:
const initialAppState = {
showSideBar: false,
showSwitcher: false,
showRightPane: false,
menu: [
{
name: "Home",
redirect: "/",
},
{
name: "About",
redirect: "/about",
expanded: false,
childs: [{
name: "Child one",
redirect: "/Child"
}]
},
]
}
除此之外,我还有一个 Pane.js 和 Menu.js 来呈现我的菜单列表。
Pane.js
const LeftPane = (props) => {
return <List>
{links.map((o, index) => {
return <Menus key={o.name} props={o} index={index} />
})}
</List>
}
Menu.js
const Menus = ({ props, index, onToggleSubMenu }) => {
return <ListItem> ...
}
我正在尝试将菜单对象的扩展值更新为 true,但是当我使用 state.menu.map 更改值时,我的反应组件不会重新渲染?它将执行到 Pane.js,我可以从 Pane.js 道具中看到扩展 = true。但它不会执行到 Menu.js?
const AppReducer = (state = initialAppState, action) => {
return {...state,
menu: [
...state.menu.map((m, i) => {
if (i === action.index) {
m.expanded = !state.menu[action.index].expanded;
}
return m;
})
]
}
}
另一方面,如果我从下面的代码中更新扩展值,它会起作用。
const AppReducer = (state = initialAppState, action) => {
state.menu[action.index] = Object.assign({}, state.menu[action.index], {
expanded: !state.menu[action.index].expanded,
});
return {...state, menu: state.menu}
}
这两者有什么不同?更新状态的正确方法是什么?为什么我们应该使用 Object.assign 或 spread (...) 操作符来更新状态?我已经阅读了Redux Immutale Update Patterns,上面的工作代码更像是链接中提到的常见错误。
【问题讨论】: