我有以下代码:
用户 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
。为什么会这样?
最佳答案
在 shouldComponentUpdate
中,您正在打印 this.props.user
,这将在 props 更改之前打印它们。如果你想打印改变的 Prop ,你应该打印 nextProps
。现在,当 shouldComponentUpdate
返回 true
时,React 使用 nextProps
更新 this.props
。然后调用 render
并因此记录更改的用户。这按预期工作。
关于javascript - shouldComponentUpdate() Prop 不同于 render() Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47590464/