我有以下代码:
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
。为什么会这样?
答案 0 :(得分:6)
在shouldComponentUpdate
中,您正在打印this.props.user
,它会在更改之前打印道具。如果要打印更改的道具,则应打印nextProps
。现在,当shouldComponentUpdate
返回true
时,React会使用this.props
更新nextProps
。然后调用render
,因此它记录更改的用户。这是按预期工作的。