Don't bind callbacks to setState, setProps etc.

We added a bind to the public instance, but instead we can just pass the
public instance as the context when we execute.

This avoids a warning that fires when we call bind on auto-bound methods.
This commit is contained in:
Sebastian Markbage 2015-01-15 14:00:45 -08:00
parent 251d31a515
commit d7d3ea5560
4 changed files with 48 additions and 6 deletions

View File

@ -712,7 +712,7 @@ var ReactClassMixin = {
);
internalInstance.replaceState(
newState,
callback && callback.bind(this)
callback
);
},
@ -746,7 +746,7 @@ var ReactClassMixin = {
);
internalInstance.setProps(
partialProps,
callback && callback.bind(this)
callback
);
},
@ -762,7 +762,7 @@ var ReactClassMixin = {
replaceProps: function(newProps, callback) {
ReactInstanceMap.get(this).replaceProps(
newProps,
callback && callback.bind(this)
callback
);
}
};

View File

@ -124,4 +124,46 @@ describe('autobinding', function() {
expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1);
});
it('warns if you try to bind to this', function() {
spyOn(console, 'warn');
var TestBindComponent = React.createClass({
handleClick: function() { },
render: function() {
return <div onClick={this.handleClick.bind(this)} />;
}
});
ReactTestUtils.renderIntoDocument(<TestBindComponent />)
expect(console.warn.argsForCall.length).toBe(1);
expect(console.warn.argsForCall[0][0]).toContain(
'You are binding a component method to the component. ' +
'React does this for you automatically'
);
});
it('does not warn if you pass an auto-bound method to setState', function() {
spyOn(console, 'warn');
var TestBindComponent = React.createClass({
getInitialState: function() {
return { foo: 1 };
},
componentDidMount: function() {
this.setState({ foo: 2 }, this.handleUpdate);
},
handleUpdate: function() {
},
render: function() {
return <div onClick={this.handleClick} />;
}
});
ReactTestUtils.renderIntoDocument(<TestBindComponent />)
expect(console.warn.argsForCall.length).toBe(0);
});
});

View File

@ -152,7 +152,7 @@ function runBatchedUpdates(transaction) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(
callbacks[j],
component
component.getPublicInstance()
);
}
}

View File

@ -61,7 +61,7 @@ ReactComponentBase.prototype.setState = function(partialState, callback) {
'component.'
);
internalInstance.setState(
partialState, callback && callback.bind(this)
partialState, callback
);
};
@ -87,7 +87,7 @@ ReactComponentBase.prototype.forceUpdate = function(callback) {
'components. This usually means you called forceUpdate() on an ' +
'unmounted component.'
);
internalInstance.forceUpdate(callback && callback.bind(this));
internalInstance.forceUpdate(callback);
};
/**