Skip to content

Commit 35ccbd6

Browse files
committed
getDerivedStateFromProps
1 parent 068a908 commit 35ccbd6

File tree

2 files changed

+17
-17
lines changed

2 files changed

+17
-17
lines changed

src/Component.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,16 @@ class Updater {
5757
state = { ...state, ...nextState };
5858
});
5959

60+
if (this.classInstance.constructor.getDerivedStateFromProps) {
61+
const partialState = this.classInstance.constructor.getDerivedStateFromProps(
62+
this.nextProps,
63+
this.classInstance.state
64+
);
65+
if (partialState) {
66+
state = { ...state, ...partialState };
67+
}
68+
}
69+
6070
this.pendingStates.length = 0;
6171
return state;
6272
}
@@ -133,16 +143,6 @@ function shouldUpdate(classInstance, nextProps, nextState) {
133143
classInstance.props = nextProps;
134144
}
135145

136-
if (classInstance.constructor.getDerivedStateFromProps) {
137-
const partialState = classInstance.constructor.getDerivedStateFromProps(
138-
nextProps,
139-
classInstance.state
140-
);
141-
if (partialState) {
142-
nextState = { ...nextState, ...partialState };
143-
}
144-
}
145-
146146
classInstance.state = nextState; // 不管组件是否刷新,组件的state一定要改变
147147

148148
if (willUpdate) {

src/index.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ class Counter2 extends React.Component {
143143
};
144144

145145
handleClick2 = () => {
146-
this.forceUpdate()
146+
this.forceUpdate();
147147
};
148148

149149
render() {
@@ -192,10 +192,10 @@ class ChildCounter extends React.Component {
192192
};
193193
}
194194

195-
// shouldComponentUpdate(nextProps, nextState) {
196-
// console.log('子组件 子组件是否更新');
197-
// return nextProps.count % 3 === 0;
198-
// }
195+
shouldComponentUpdate(nextProps, nextState) {
196+
console.log('子组件 子组件是否更新', nextProps, nextState);
197+
return nextProps.count % 3 === 0;
198+
}
199199

200200
// componentWillUpdate() {
201201
// console.log('子组件 will update');
@@ -210,8 +210,8 @@ class ChildCounter extends React.Component {
210210
// }
211211

212212
render() {
213-
console.log('子组件 render');
214-
return <div id={`child-${this.props.count}`}>{this.state.number}</div>;
213+
console.log('子组件 render', this.props);
214+
return <div>{this.state.number}</div>;
215215
}
216216
}
217217

0 commit comments

Comments
 (0)