组件的ShouldComponentUpdate中进行深度比较吗?"/>
在Redux Reducer或组件的ShouldComponentUpdate中进行深度比较吗?
在我的React Redux应用程序中,setInterval()
连续调用查询REST API端点的动作创建器this.props.getLatestNews()
。在获取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中,当前总是更新部分状态,无论是否有任何更改
减速器
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存储库中不存在不存在的新项目。
[为了避免不必要地重新渲染React组件,我在考虑对shouldComponentMount()
函数中的当前道具和下一个道具进行深度比较,或者对action.payload
与state.items
进行深度比较。 ]应该将其替换。
建议在哪里进行深度比较?还是根本不需要?
谢谢!
回答如下:一般来说,在使用redux时,我们有几种选择可以避免重新渲染。
更多推荐
在Redux Reducer或组件的ShouldComponentUpdate中进行深度比较吗?
发布评论