代码之家  ›  专栏  ›  技术社区  ›  Nyxynyx

深入比较Redux Reducer或组件ShouldComponentUpdate?

  •  0
  • Nyxynyx  · 技术社区  · 6 年前

    在我的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

    建议在哪里进行深度比较?或者这根本没有必要?

    谢谢您!

    0 回复  |  直到 6 年前
        1
  •  1
  •   gdh    6 年前

    一般来说,在使用redux时,我们可以做出很少的选择来避免重新渲染。

    1. 异径管: 比较当前状态和api/操作有效负载结果,即您的未来状态/下一个状态。只是
    2. 组件内 shouldComponentUpdate 这给了你 nextProps nextState 作为论据。
    3. 在行动中 :如果要执行条件分派(即,如果对api结果不满意,则分派其他内容),则在操作中执行比较。你可以用 getState 访问当前状态。

    注意-即使使用纯组件,组件仍将重新渲染,因为即使对象值相同,状态的对象引用也会更改。

    第1点演示- 应更新组件

    Edit shouldcomponent update fix

    state-reducer-etc

    Edit react+redux+reducer+test

    推荐文章