shouldComponentUpdate()与render()props不同

时间:2017-12-01 09:38:24

标签: javascript reactjs react-native redux react-redux

我有以下代码:

user reducer

const initialState = {
    user: undefined,
    isFetching: true,
    error: false
}

export default (state = initialState, action) => {
    switch (action.type) {
        case 'FETCHING_USER':
            return {
                ...state,
                isFetching: true,
                user: undefined
            }
        case 'FETCHING_USER_SUCCESS':
            return {
                ...state,
                isFetching: false,
                user: action.data
            }
        default:
            return state
    }
}

actions.js

export function getUser() {
    return async (dispatch) => {
        console.log('Fetching...');
        dispatch(({ type: 'FETCHING_USER' }));
        const data = await (await fetch(new Request('http://...', {
            headers: new Headers({
                'Content-Type': 'application/json',
                'access-key': '<key>'
            })
        }))).json();
        dispatch({ type: 'FETCHING_USER_SUCCESS', data });
    }
}

profile-picture.js

@connect(state => ({ user: state.user }))
export default class ProfilePicture extends Component {
    shouldComponentUpdate(nextProps) {
        console.log('SHOULDCOMPONENTUPDATE USER: ', this.props.user);
        return true;
    }

    render() {
        console.log('RENDER USER: ', this.props.user);
        return( ...
    }
}

产生以下输出:

11:31:22 AM
SHOULDCOMPONENTUPDATE USER:  Object {
  "error": false,
  "isFetching": true,
  "user": undefined,
}
11:31:22 AM
RENDER USER:  Object {
  "error": false,
  "isFetching": false,
  "user": Object {
    "desiredEnvironment": null,
    "email": "abc@abc.net",
    "expectations": null,
    "firstNme": "Iuliu",
    ...

在具有相同输出的每个渲染上发生这种情况几次。我正在尝试实现shouldComponentUpdate以减少不必要的渲染。据我所知,shouldComponentUpdate始终收到initialState。为什么会这样?

1 个答案:

答案 0 :(得分:6)

shouldComponentUpdate中,您正在打印this.props.user,它会在更改之前打印道具。如果要打印更改的道具,则应打印nextProps。现在,当shouldComponentUpdate返回true时,React会使用this.props更新nextProps。然后调用render,因此它记录更改的用户。这是按预期工作的。