我有以下代码: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": "[email protected]",
"expectations": null,
"firstNme": "Iuliu",
...
在具有相同输出的每个渲染上,这种情况会发生几次。我正在尝试实现
shouldComponentUpdate
以减少不必要的渲染。从我可以看到的是,shouldComponentUpdate
总是收到initialState
。为什么会这样呢? 最佳答案
在shouldComponentUpdate
中,您正在打印this.props.user
,这将在更改道具之前打印道具。如果要打印更改的道具,则应打印nextProps
。现在,当shouldComponentUpdate
返回true
时,React用this.props
更新nextProps
。然后,调用render
并因此记录更改的用户。这正在按预期方式工作。