iul*_*net 1 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
}
}
Run Code Online (Sandbox Code Playgroud)
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 });
}
}
Run Code Online (Sandbox Code Playgroud)
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( ...
}
}
Run Code Online (Sandbox Code Playgroud)
其中产生以下输出:
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",
...
Run Code Online (Sandbox Code Playgroud)
对于具有相同输出的每个渲染,这会发生几次.我试图实现shouldComponentUpdate减少不必要的渲染.从我所看到的,shouldComponentUpdate总有收到的initialState.为什么会这样?
在shouldComponentUpdate,您正在打印this.props.user,它将在更改之前打印道具.如果要打印已更改的道具,则应打印nextProps.现在,作为shouldComponentUpdate回报true,更新做出反应this.props用nextProps.然后render调用它,因此它记录更改的用户.这是按预期工作的.
| 归档时间: |
|
| 查看次数: |
281 次 |
| 最近记录: |