在我的React Redux应用程序中
setInterval()
连续调用动作创建者
this.props.getLatestNews()
查询RESTAPI终结点。在获取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
});
...
props
除非我们做一个深入的比较
shouldComponentUpdate()
shouldComponentMount()
action.payload
具有
state.items
建议在哪里进行深度比较?或者这根本没有必要?
谢谢您!