Skip to content

Commit ef23055

Browse files
author
Keyan Zhang
committed
improved the logic of repositioning state property
1 parent d7083fe commit ef23055

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

transforms/__testfixtures__/class-initial-state.input.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,19 @@ var MyComponent4 = React.createClass({
107107
},
108108
});
109109

110+
// but only accessing `this.props` and/or `this.context` is safe
111+
var MyComponent5 = React.createClass({
112+
getInitialState: function() {
113+
return {
114+
heyoo: getContextFromInstance(this.props),
115+
};
116+
},
117+
118+
foo: function(): void {
119+
this.setState({heyoo: 24});
120+
},
121+
});
122+
110123
// intense control flow testing
111124
var Loader = React.createClass({
112125
getInitialState() {

transforms/__testfixtures__/class-initial-state.output.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,17 @@ class MyComponent4 extends React.Component {
114114
};
115115
}
116116

117+
// but only accessing `this.props` and/or `this.context` is safe
118+
class MyComponent5 extends React.Component {
119+
state = {
120+
heyoo: getContextFromInstance(this.props),
121+
};
122+
123+
foo = (): void => {
124+
this.setState({heyoo: 24});
125+
};
126+
}
127+
117128
// intense control flow testing
118129
class Loader extends React.Component {
119130
constructor(props, context) {

transforms/class.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,27 @@ module.exports = (file, api, options) => {
788788

789789
// to ensure that our property initializers' evaluation order is safe
790790
const repositionStateProperty = (initialStateProperty, propertiesAndMethods) => {
791-
if (j(initialStateProperty).find(j.ThisExpression).size() === 0) {
791+
const initialStateCollection = j(initialStateProperty);
792+
const thisCount = initialStateCollection.find(j.ThisExpression).size();
793+
const safeThisMemberCount = initialStateCollection.find(j.MemberExpression, {
794+
object: {
795+
type: 'ThisExpression',
796+
},
797+
property: {
798+
type: 'Identifier',
799+
name: 'props',
800+
},
801+
}).size() + initialStateCollection.find(j.MemberExpression, {
802+
object: {
803+
type: 'ThisExpression',
804+
},
805+
property: {
806+
type: 'Identifier',
807+
name: 'context',
808+
},
809+
}).size();
810+
811+
if (thisCount === safeThisMemberCount) {
792812
return initialStateProperty.concat(propertiesAndMethods);
793813
}
794814

0 commit comments

Comments
 (0)