将反应组件绑定到部分 redux 状态
Bind react component to part of redux state
我有看起来像这样的 redux 商店:
{
user: {},
alerts: [],
reports: [],
sourses: []
}
对于状态的每个部分,我都有一堆 React 组件包裹在通过 react-redux
连接的容器中。并且有 mapStateToProps
这样的
(state) => {alerts: state.alerts}
(state, ownProps) => {alert: _.filter(state, {id: ownProps.curId})}
问题是,当我例如为 CREATE_ALERT
或 EDIT_ALERT
之类的警报启动某些操作并更新 redux 状态时,ALL REACT 组件将响应此更改 甚至那些与 sources
或 reports
.
等不同部分一起工作的
我的问题:如何 "bind" 某些组件到树的某些部分。因此,每个容器组件 仅在 REDUX 状态的适当部分更新时更新 并忽略其他更改。
预期行为
Dispatch CREATE_ALERT
-> Alert reducer -> Redux store update -> ONLY Alert container component re-rendering.
当你在 redux 中改变状态时,整个状态变成了一个新对象。
然后你的组件由这个新对象(新引用)给出并重新渲染它自己。
要修复此行为,您需要添加一些逻辑来比较您的组件是否具有不同值的道具(不是引用)。
最简单和最快的方法是使用 React.PureComponent。您也可以覆盖 shouldComponentUpdate
函数并自行处理更改。但请注意 PureComponent
仅适用于基元(它进行浅比较)。
另请检查 Immutable.js,它可以帮助您智能地更改道具的引用。
如果你使用 connect 方法,那么只将选定的 redux 状态传递给组件,这将阻止其他组件的渲染
示例:
用户组件:
const mapStateToProps = state =>({
users: state.users
});
export default connect(mapStateToProps)(User)
警报组件:
const mapStateToProps = state =>({
alerts: state.alerts
});
export default connect(mapStateToProps)(Alert)
看看这个:Avoid Reconciliation
那里解释了 Neciu 所说的内容。
使用 connect
创建的容器组件将始终收到商店所有更新的通知。
使用这些更新的责任落在接收 connect
组件上。它应该包含提取与其相关的数据的逻辑。
我有看起来像这样的 redux 商店:
{
user: {},
alerts: [],
reports: [],
sourses: []
}
对于状态的每个部分,我都有一堆 React 组件包裹在通过 react-redux
连接的容器中。并且有 mapStateToProps
这样的
(state) => {alerts: state.alerts}
(state, ownProps) => {alert: _.filter(state, {id: ownProps.curId})}
问题是,当我例如为 CREATE_ALERT
或 EDIT_ALERT
之类的警报启动某些操作并更新 redux 状态时,ALL REACT 组件将响应此更改 甚至那些与 sources
或 reports
.
我的问题:如何 "bind" 某些组件到树的某些部分。因此,每个容器组件 仅在 REDUX 状态的适当部分更新时更新 并忽略其他更改。
预期行为
Dispatch CREATE_ALERT
-> Alert reducer -> Redux store update -> ONLY Alert container component re-rendering.
当你在 redux 中改变状态时,整个状态变成了一个新对象。 然后你的组件由这个新对象(新引用)给出并重新渲染它自己。
要修复此行为,您需要添加一些逻辑来比较您的组件是否具有不同值的道具(不是引用)。
最简单和最快的方法是使用 React.PureComponent。您也可以覆盖 shouldComponentUpdate
函数并自行处理更改。但请注意 PureComponent
仅适用于基元(它进行浅比较)。
另请检查 Immutable.js,它可以帮助您智能地更改道具的引用。
如果你使用 connect 方法,那么只将选定的 redux 状态传递给组件,这将阻止其他组件的渲染
示例:
用户组件:
const mapStateToProps = state =>({
users: state.users
});
export default connect(mapStateToProps)(User)
警报组件:
const mapStateToProps = state =>({
alerts: state.alerts
});
export default connect(mapStateToProps)(Alert)
看看这个:Avoid Reconciliation
那里解释了 Neciu 所说的内容。
使用 connect
创建的容器组件将始终收到商店所有更新的通知。
使用这些更新的责任落在接收 connect
组件上。它应该包含提取与其相关的数据的逻辑。