![](/img/trans.png)
[英]Optimizing react redux component with shouldComponentUpdate
[英]Deep Compare in Redux Reducer or in Component's ShouldComponentUpdate?
在我的 React Redux 应用程序中, setInterval()
不断调用操作this.props.getLatestNews()
来查询 REST ZDB974238714CA8DE634A7CE1D083A14F 端点。 在获得 API 响应(对象数组)后,它将以响应数组作为有效负载分派一个动作。
反应组件
class Newsfeed extends Component {
constructor(props) {
super(props);
this.state = { ... }
}
componentWillMount() {
this.updateTimer = setInterval(() => { this.props.getLatestNews() }, 1000);
}
componentWillUnmount() {
clearInterval( this.updateTimer );
}
shouldComponentUpdate(nextProps, nextState) {
// Should we do a deep compare of nextProps & this.props,
// shallow compare of nextState & thisState?
}
render() {
return ( ... )
}
}
const mapStateToProps = (state) => ({
newsfeed: state.newsfeed
});
const mapDispatchToProps = (dispatch) => {
return {
getLatestNews: () => dispatch(getLatestNews())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Newsfeed);
在reducer中,目前一直更新部分state,不管有没有变化
减速器
export default function newsfeedReducer(state=initialState, action) {
switch (action.type) {
case NEWSFEED_RECEIVED:
// Or should we do the deep compare of `action.payload` with `state.items` here?
return { ...state, items: action.payload }
default:
return state
}
}
根减速器
...
const rootReducer = combineReducers({
newsfeed: newsfeedReducer
});
...
大多数情况下,当收到 API 结果时,Redux 存储中没有不存在的新项目。 如果 reducer 仍然用 API 结果替换 store 的这一部分,则连接的组件将由于新的 object 对props
的引用而重新渲染,除非我们在shouldComponentUpdate()
中进行深入比较。
为了避免对 React 组件进行不必要的重新渲染,我正在考虑对shouldComponentMount()
function 中的当前和下一个道具进行深度比较,或者对action.payload
与state.items
进行深度比较它应该替换。
进行深度比较的推荐位置在哪里? 或者这根本没有必要?
谢谢!
通常,在使用 redux 时,我们可以做的选择很少,以避免重新渲染。
shouldComponentUpdate
它将为您提供nextProps
和nextState
作为 arguments。注意 - 即使您使用纯组件,组件仍将重新渲染,因为即使 object 值相同,状态的 object 参考也会更改。
第 1 点的演示 - shouldComponentUpdate
第 2 点的演示 - state-reducer-etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.