Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introducing ReactComponentBase base class #2805

Merged
merged 1 commit into from
Jan 13, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/browser/ui/React.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ var DOMPropertyOperations = require('DOMPropertyOperations');
var EventPluginUtils = require('EventPluginUtils');
var ReactChildren = require('ReactChildren');
var ReactComponent = require('ReactComponent');
var ReactComponentBase = require('ReactComponentBase');
var ReactClass = require('ReactClass');
var ReactContext = require('ReactContext');
var ReactCurrentOwner = require('ReactCurrentOwner');
Expand Down Expand Up @@ -57,6 +58,7 @@ var React = {
count: ReactChildren.count,
only: onlyChild
},
Component: ReactComponentBase,
DOM: ReactDOM,
PropTypes: ReactPropTypes,
initializeTouchEvents: function(shouldUseTouch) {
Expand Down
72 changes: 6 additions & 66 deletions src/classic/class/ReactClass.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

"use strict";

var ReactComponentBase = require('ReactComponentBase');
var ReactElement = require('ReactElement');
var ReactErrorUtils = require('ReactErrorUtils');
var ReactInstanceMap = require('ReactInstanceMap');
Expand All @@ -22,7 +23,6 @@ var invariant = require('invariant');
var keyMirror = require('keyMirror');
var keyOf = require('keyOf');
var monitorCodeUse = require('monitorCodeUse');
var warning = require('warning');

var MIXINS_KEY = keyOf({mixins: null});

Expand Down Expand Up @@ -692,49 +692,11 @@ function bindAutoBindMethods(component) {
}

/**
* @lends {ReactClass.prototype}
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponentBase.
*/
var ReactClassMixin = {

/**
* Sets a subset of the state. Always use this or `replaceState` to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
setState: function(partialState, callback) {
invariant(
typeof partialState === 'object' || partialState == null,
'setState(...): takes an object of state variables to update.'
);
if (__DEV__) {
warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().'
);
}
var internalInstance = ReactInstanceMap.get(this);
invariant(
internalInstance,
'setState(...): Can only update a mounted or mounting component.'
);
internalInstance.setState(
partialState, callback && callback.bind(this)
);
},

/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
Expand All @@ -743,38 +705,15 @@ var ReactClassMixin = {
var internalInstance = ReactInstanceMap.get(this);
invariant(
internalInstance,
'replaceState(...): Can only update a mounted or mounting component.'
'replaceState(...): Can only update a mounted or mounting component. ' +
'This usually means you called replaceState() on an unmounted component.'
);
internalInstance.replaceState(
newState,
callback && callback.bind(this)
);
},

/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldUpdateComponent`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
forceUpdate: function(callback) {
var internalInstance = ReactInstanceMap.get(this);
invariant(
internalInstance,
'forceUpdate(...): Can only force an update on mounted or mounting ' +
'components.'
);
internalInstance.forceUpdate(callback && callback.bind(this));
},

/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
Expand Down Expand Up @@ -829,6 +768,7 @@ var ReactClassMixin = {
var ReactClassBase = function() {};
assign(
ReactClassBase.prototype,
ReactComponentBase.prototype,
ReactClassMixin
);

Expand Down
80 changes: 78 additions & 2 deletions src/core/__tests__/ReactCompositeComponent-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,8 @@ describe('ReactCompositeComponent', function() {
instance.forceUpdate();
}).toThrow(
'Invariant Violation: forceUpdate(...): Can only force an update on ' +
'mounted or mounting components.'
'mounted or mounting components. This usually means you called ' +
'forceUpdate() on an unmounted component.'
);
});

Expand Down Expand Up @@ -327,10 +328,39 @@ describe('ReactCompositeComponent', function() {
instance.setState({ value: 2 });
}).toThrow(
'Invariant Violation: setState(...): Can only update a mounted or ' +
'mounting component.'
'mounting component. This usually means you called setState() on an ' +
'unmounted component.'
);
});

it('should not allow `setState` on unmounting components', function() {
var container = document.createElement('div');
document.documentElement.appendChild(container);

var Component = React.createClass({
getInitialState: function() {
return { value: 0 };
},
componentWillUnmount: function() {
expect(() => this.setState({ value: 2 })).toThrow(
'Invariant Violation: replaceState(...): Cannot update while ' +
'unmounting component. This usually means you called setState() ' +
'on an unmounted component.'
);
},
render: function() {
return <div />;
}
});

var instance = React.render(<Component />, container);
expect(function() {
instance.setState({ value: 1 });
}).not.toThrow();

React.unmountComponentAtNode(container);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't actually unmount in most of our tests. I think you could skip this, as well as appending container to the DOM (non of our tests do this, just having the node is good enough)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is testing componentWillUnmount so I need to unmount it to trigger the expect in the test case.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, sorry, I missed that.

});

it('should not allow `setProps` on unmounted components', function() {
var container = document.createElement('div');
document.documentElement.appendChild(container);
Expand Down Expand Up @@ -623,6 +653,31 @@ describe('ReactCompositeComponent', function() {
);
});

it('only renders once if updated in componentWillReceiveProps', function() {
var renders = 0;
var Component = React.createClass({
getInitialState: function() {
return { updated: false };
},
componentWillReceiveProps: function(props) {
expect(props.update).toBe(1);
this.setState({ updated: true });
},
render: function() {
renders++;
return <div />;
}
});

var container = document.createElement('div');
var instance = React.render(<Component update={0} />, container);
expect(renders).toBe(1);
expect(instance.state.updated).toBe(false);
React.render(<Component update={1} />, container);
expect(renders).toBe(2);
expect(instance.state.updated).toBe(true);
});

it('should update refs if shouldComponentUpdate gives false', function() {
var Static = React.createClass({
shouldComponentUpdate: function() {
Expand Down Expand Up @@ -659,4 +714,25 @@ describe('ReactCompositeComponent', function() {
expect(comp.refs.static1.getDOMNode().textContent).toBe('A');
});

it('should allow access to getDOMNode in componentWillUnmount', function() {
var a = null;
var b = null;
var Component = React.createClass({
componentDidMount: function() {
a = this.getDOMNode();
},
componentWillUnmount: function() {
b = this.getDOMNode();
},
render: function() {
return <div />;
}
});
var container = document.createElement('div');
expect(a).toBe(container.firstChild);
React.render(<Component />, container);
React.unmountComponentAtNode(container);
expect(a).toBe(b);
});

});
127 changes: 127 additions & 0 deletions src/modern/class/ReactComponentBase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentBase
*/

"use strict";

var ReactInstanceMap = require('ReactInstanceMap');

var assign = require('Object.assign');
var invariant = require('invariant');
var warning = require('warning');

/**
* Base class helpers for the updating state of a component.
*/
function ReactComponentBase(props) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if we actually use ES6 classes in our src? It gets compiled down to this and the ReactComponentBase.prototype.* = ...

It's not a big deal but could be nice to start doing.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't fully trust the transpilers that we use to be efficient since classes have to deal with other edge cases. For example, we might start including a runtime in the transpiler.

They may also not always be spec compliant. It might not be equivalent since class methods are probably going to become non-enumerable which we can't do in IE8. But that has gone back and forth.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's fair. Not a big deal. We've gone the prototype route in the past too.

this.props = props;
}

/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
ReactComponentBase.prototype.setState = function(partialState, callback) {
invariant(
typeof partialState === 'object' || partialState == null,
'setState(...): takes an object of state variables to update.'
);
if (__DEV__) {
warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().'
);
}

var internalInstance = ReactInstanceMap.get(this);
invariant(
internalInstance,
'setState(...): Can only update a mounted or mounting component. ' +
'This usually means you called setState() on an unmounted ' +
'component.'
);
internalInstance.setState(
partialState, callback && callback.bind(this)
);
};

/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldUpdateComponent`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
ReactComponentBase.prototype.forceUpdate = function(callback) {
var internalInstance = ReactInstanceMap.get(this);
invariant(
internalInstance,
'forceUpdate(...): Can only force an update on mounted or mounting ' +
'components. This usually means you called forceUpdate() on an ' +
'unmounted component.'
);
internalInstance.forceUpdate(callback && callback.bind(this));
};

/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
if (__DEV__) {
if (Object.defineProperty) {
var deprecatedAPIs = {
getDOMNode: 'getDOMNode',
isMounted: 'isMounted',
replaceState: 'replaceState',
setProps: 'setProps'
};
var defineDeprecationWarning = function(methodName, displayName) {
Object.defineProperty(ReactComponentBase.prototype, methodName, {
get: function() {
warning(
false,
'%s(...) is deprecated in plain JavaScript React classes.',
displayName
);
return undefined;
}
});
};
for (var methodName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(methodName)) {
defineDeprecationWarning(methodName, deprecatedAPIs[methodName]);
}
}
}
}

module.exports = ReactComponentBase;
Loading