I was trying to pass props from parent to child component.
While I was calling this.props inside render its working fine But when I am calling it inside function which will not render (help me do calculation) the console value is "undefined".
Please answer this question with explanation?
Is the function member of the class? In other words, has the function been bind to the class?
Value will be undefined if the function doesn't know what class it belong to. Bind it to a class, then you'll get your value.
For instance -
An unbinded function will look like this
abc() {
console.log(this); //this will be undefined here
}
A binded function will look like this
constructor() {
this.abc = this.abc.bind(this);
}
abc() {
console.log(this); //this will have a value
}
In case, you want to skip writing bind you can follow the new syntax
abc = () => {
console.log(this); //this will have a value
}
Finally, you'll be calling your function like this.abc()
Please bind the function to the class either in the constructor or using .bind
Related
I am new on react
I tried to execute this function in react
export default class App extends Component{
render(){
function SSS(t)
{
this.t=t;
return this;
}
console.log(SSS(1).t);
}return(
<h1>H</h1>
)}
}
but it still gives me that error
TypeError: Cannot set property 't' of undefined
I read about "this" in MDN
they mentioned the reason of this error is how to call the function
it works perfectly on js pure.
could you help me with that,please ?
thnx!
SSS function call should assign t variable onto its execution context, e.g., if you call it in within window object, the variable can be accessed from there,
window.t // 1. Provided you are in 'use strict' mode., you will get
TypeError: Cannot set property 't' of undefined
If you want to bind custom context to SSS, you should either use call/apply/bind, examples:
SSS.call({}, 1)
SSS.apply({}, [1])
SSS.bind({})(1);
or constructor call:
new SSS(1);
Welcome to StackOverflow.
You're using "this" in a function-in-function, "this" is not defined there.
What you want is put SSS(t) outside of render, as a class method.
Like this:
export default class App extends Component{
SSS(t)
{
this.t=t;
return this;
}
render(){
console.log(this.SSS(1).t);
return(
<h1>H</h1>
);
}
}
Also, not that doing this.t = t is dangerous in React. You should probably use this.state.t and this.setState() instead. Check this for more info :
Why can't I directly modify a component's state, really?
https://reactjs.org/docs/state-and-lifecycle.html
Let's say I have this function in the parent component which just mutates the text formatting:
combineName(name) {
const joinName = name.replace(/\s/g, '');
return joinName[0].toLowerCase() + joinName.substr(1);
}
Then in my parent component's render() method, I have:
render() {
return (
<h1 id={this.combineName.bind(this, name)()}>
)
}
Which immediately invokes the combineName function upon render. This is working. However inside my parent component, I also have a child component like so:
<SectionBody
combineName={this.combineName}
/>
My problem is how do I use this inside the child component in the way I used it in the parent component?
Do I simply call it like so:
this.props.combineName(param)?
this.props.combineName(param)
this should work like a charm.
I would prefer to make these changes as well, I think you're binding it in your constructor but still it's preferable to use es6 arrow function which auto binds this to handler:
combineName = name => {
const joinName = name.replace(/\s/g, '');
return joinName[0].toLowerCase() + joinName.substr(1);
}
Yes you have to call it like
this.props.combineName(param)
This will work fine:
<SectionBody
combineName={this.props.combineName}
/>
I have a quite big React.Component with more than ten bind(this) calls in its constructor.
I don't think .bind(this) in a constructor gives any help to understand my code especially when reading the code inside of render().
So, I came up with the following idea, however, do not find how to achieve this.
render() {
if (this.methodToBind.getThis() === this) {
this.methodToBind = this.methodToBind.bind(this);
}
}
Is there any possible way I can get this of a method (getThis() from the example above)?
If yes for the above, is it a good practice to do this?
rather then doing this,
constructor () {
super();
this.myFunc = this.myFunc.bind(this);
}
myFunc () {
// code here
}
You can do something like this.
constructor () {
super();
// leave the binding, it's just not what the cool kids do these days
}
myFunc = () => {
// see what I did here with = () => {}
// this will bind your `this` with it's parent
// lexical context, which is your class itself, cool right. Do this!
}
For a reference have a look at the MDN documentation for Arrow Functions
Where to Bind This?
When you create a function in a Class Based Component in React.js you must bind this in order to call it from the render method. Otherwise the function will not be in scope.
There are a few ways to do this.
Never bind this in the render method. Binding this in the render method will cause React to create a new function every time your Component is rerendered. This is why we most commonly bind in the constructor.
Bind in the constructor. By binding in the constructor, you can call your function in the render method by using this.FunctionName();
Example Bind This
Class MyClass extends Component {
constructor(props) {
super(props);
this.FunctionName = this.FunctionName.bind(this);
}
myFunc () {
// code here
}
render() {
this.FunctionName();
return(
<div>
...
</div>
);
}
}
User fat arrow functions instead of traditional function definitions. Fat arrow functions lexically bind the this value. So you do not have to add bind to the function in the constructor when you use the fat arrow function in the class.
Important - Fat arrow functions are not always available to use in a React class. Depending on how you setup React. You might have to install,
babel-plugin-transform-class-properties
Then add it to your .bablerc file like this,
{
"plugins": [
"transform-class-properties"
],
"presets": [
"react"
]
}
Example Fat Arrow
Class MyClass extends Component {
myFunc = () => {
// code here
}
render() {
this.FunctionName();
return(
<div>
...
</div>
);
}
}
Summary
Never bind a function in the render.
Always bind in the constructor when using a traditional function
this is automatically available on the function when using a fat arrow function.
Not sure.
I am usually doing something like this:
onClick={this.handleClick.bind(this)}
or:
onClick={e => this.handleClick(e)}
I have a question relavent to this code: https://github.com/reactjs/redux/blob/master/examples/async/containers/App.js
specifically:
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.handleRefreshClick = this.handleRefreshClick.bind(this)
}
I guess its a 2 part question.
Why do I need to set handle change as an instance of class this.handleChange =, can't I just use static functions for handleChange and call it directly with in the class onClick={handleRefreshClick}> ?
I have no idea whats going on here: this.handleRefreshClick.bind(this)
Thanks
Answered in reverse order...
this.handleRefreshClick.bind(something) returns a new function, in which references to this will refer to something. This is a way of saving the current value of this, which is in scope during the call to the constructor, so that it can be used later when the function is called.
If your functions don't require access to the state of your component, then sure, you don't need to bind them.
The argument in favour of adding these lines to the constructor is so that the new bound functions are only created once per instance of the class. You could also use
onClick={this.handleRefreshClick.bind(this)}
or (ES6):
onClick={() => this.handleRefreshClick()}
but either of these methods will create a new function every time the component is re-rendered.
The reason why it's being done, is to bind the this keyword to that object. Like Tom said, calling a function from a class doesn't mean it's being called with the context of the object that created that function.
I think you might be getting confused because in the React examples/tutorials, using React.createClass() DOES bind this automatically for you. So you might be wondering why React.createClass() does it, but doesn't with ES6 class syntax.
This is because React didn't want to mess with ES6 specifications (binding this to functions from its class is not in the ES6 class spec), but at the same time, wanted to give its users the convenience of ES6 class syntax. You can read more about this below.
Github issue
Hopefully that sheds some light on why that happens.
this depends how the function is called, not how/where it is created.
When you look at the code, you see two "this", why? Seems weird, right?
The thing is it is not about how it seems. It is about how it is called.
You are basically saying. Hey, when somebody calls you remember this means this class. not something else.
When somebody calls your class like: x.yourClass().bind(this) you are saying this is not x but the class itself(with props and states etc.).
Quick note, even when you call directly the class like yourClass() you are actually calling window.yourClass() on browser, also that is why in this case the this is window.
These 2 functions handleChange and handleRefreshClick are passed down as props to other components ,
They are bind to this because when the child component will call these functions they will always execute with the APP context.
You can remove these functions from the class but still you need to bind this since you would be updating some parts of your APP
All the answers here are good, but for clarity regarding:
I have no idea whats going on here: this.handleRefreshClick.bind(this)
I think an example is best in describing the difference in behaviour.
// Class where functions are explicitly bound to "this" specific object
var Bindings = class {
constructor() {
this.Firstname = "Joe"
this.Surname = "Blow"
this.PrettyPrint = this.PrettyPrint.bind(this)
this.Print = this.Print.bind(this)
}
Print(inputStr) {
console.log(inputStr)
console.log(this)
}
PrettyPrint() {
this.Print(`${this.Firstname} ${this.Surname}`)
}
}
// Class where "this" context for each function is implicitly bound to
// the object the function is attached to / window / global
// identical class, except for removing the calls to .bind(this)
var NoBindings = class {
constructor() {
this.Firstname = "Joe"
this.Surname = "Blow"
}
Print(inputStr) {
console.log(inputStr)
console.log(this)
}
PrettyPrint() {
this.Print(`${this.Firstname} ${this.Surname}`)
}
}
var bindings = new Bindings()
var noBindings = new NoBindings()
bindings.PrettyPrint()
// > "Joe Blow"
// > Object { Firstname: "Joe", Surname: "Blow", PrettyPrint: PrettyPrint(), Print: Print() }
noBindings.PrettyPrint()
// > "Joe Blow"
// > Object { Firstname: "Joe", Surname: "Blow" }
// noBindings has both functions & everything works as we expect,
// if this is all you're doing, then there's practically little difference,
// but if we separate them from the original "this" context...
var b = { PPrint: bindings.PrettyPrint }
var nb = { PPrint: noBindings.PrettyPrint }
b.PPrint()
// > "Joe Blow"
// > Object { Firstname: "Joe", Surname: "Blow", PrettyPrint: PrettyPrint(), Print: Print() }
// PPrint calls "PrettyPrint" where "this" references the original "bindings" variable
// "bindings" has a function called "Print" which "PrettyPrint" calls
try {
nb.PPrint()
} catch (e) {
console.error(e);
}
// > TypeError: this.Print is not a function
// PPrint calls "PrettyPrint" where "this" references the new "nb" variable
// due to different "this" context, "nb" does not have a function called "Print", so it fails
// We can verify this by modifying "bindings" and seeing that it's reflected in "b"
bindings.Surname = "Schmo"
b.PPrint()
// > "Joe Schmo"
// > Object { Firstname: "Joe", Surname: "Schmo", PrettyPrint: PrettyPrint(), Print: Print() }
// We can also add a "Print" method to "nb", and see that it's called by PrettyPrint
nb.Print = function(inputStr) { console.log(inputStr); console.log(this) }
nb.PPrint()
// > undefined undefined
// > Object { PPrint: PrettyPrint(), Print: Print(inputStr) }
// The reason we get "undefined undefined",
// is because "nb" doesn't have a Firstname or Surname field.
// because, again, it's a different "this" context
I personally bind functions in constructor so that their references don't change on each re-render.
This is especially important if you are passing functions to read-only children that you don't need to get updated when their props don't change. I use react-addons-pure-render-mixin for that.
Otherwise, on each parent's re-render, binding will happen, new function reference will get created and passed to children, which is going to think that props have changed.
I am coding a simple app on reactjs-flux and everything works fine except I am receiving a warning from reactjs telling me that I am calling setState on unmounted components.
I have figured out this is because changelisteners to which components are hooked are not being removed from the store on componentWillUnmount. I know it because when I print the list of listeners from Eventemitter I see the listener which was supposed to be destroyed still there, and the list grows larger as I mount/unmount the same component several times.
I paste code from my BaseStore:
import Constants from '../core/Constants';
import {EventEmitter} from 'events';
class BaseStore extends EventEmitter {
// Allow Controller-View to register itself with store
addChangeListener(callback) {
this.on(Constants.CHANGE_EVENT, callback);
}
removeChangeListener(callback) {
this.removeListener(Constants.CHANGE_EVENT, callback);
}
// triggers change listener above, firing controller-view callback
emitChange() {
this.emit(Constants.CHANGE_EVENT);
}
}
export default BaseStore;
I paste the relevant code from a component experiencing this bug (it happens with all components, though):
#AuthenticatedComponent
class ProductsPage extends React.Component {
static propTypes = {
accessToken: PropTypes.string
};
constructor() {
super();
this._productBatch;
this._productBatchesNum;
this._activeProductBatch;
this._productBlacklist;
this._searchById;
this._searchingById;
this.state = this._getStateFromStore();
}
componentDidMount() {
ProductsStore.addChangeListener(this._onChange.bind(this));
}
componentWillUnmount() {
ProductsStore.removeChangeListener(this._onChange.bind(this));
}
_onChange() {
this.setState(this._getStateFromStore());
}
}
This is driving me pretty nuts at this point. Any ideas?
Thank you!
Short version: expect(f.bind(this)).not.toBe(f.bind(this));
Longer explanation:
The cause of the issue is that EventEmitter.removeListener requires that you pass a function you have previously registered with EventEmitter.addListener. If you pass a reference to any other function, it is a silent no-op.
In your code, you are passing this._onChange.bind(this) to addListener. bind returns a new function that is bound to this. You are then discarding the reference to that bound function. Then you try to remove another new function created by a bind call, and it's a no op, since that was never added.
React.createClass auto-binds methods. In ES6, you need to manually bind in your constructor:
#AuthenticatedComponent
class ProductsPage extends React.Component {
static propTypes = {
accessToken: PropTypes.string
};
constructor() {
super();
this._productBatch;
this._productBatchesNum;
this._activeProductBatch;
this._productBlacklist;
this._searchById;
this._searchingById;
this.state = this._getStateFromStore();
// Bind listeners (you can write an autoBind(this);
this._onChange = this._onChange.bind(this);
}
componentDidMount() {
// listener pre-bound into a fixed function reference. Add it
ProductsStore.addChangeListener(this._onChange);
}
componentWillUnmount() {
// Remove same function reference that was added
ProductsStore.removeChangeListener(this._onChange);
}
_onChange() {
this.setState(this._getStateFromStore());
}
There are various ways of simplifying binding - you could use an ES7 #autobind method decorator (e.g. autobind-decorator on npm), or write an autoBind function that you call in the constructor with autoBind(this);.
In ES7, you will (hopefully) be able to use class properties for a more convenient syntax. You can enable this in Babel if you like as part of the stage-1 proposal http://babeljs.io/docs/plugins/transform-class-properties/ . Then, you just declare your event listener methods as class properties rather than methods:
_onChange = () => {
this.setState(this._getStateFromStore());
}
Because the initializer for _onChange is invoked in the context of the constructor, the arrow function auto-binds this to the class instance so you can just pass this._onChange as an event handler without needing to manually bind it.
So I have found the solution, it turns out I only had to assign this._onChange.bind(this) to an internal property before passing it as an argument to removechangelistener and addchangelistener. Here is the solution:
componentDidMount() {
this.changeListener = this._onChange.bind(this);
ProductsStore.addChangeListener(this.changeListener);
this._showProducts();
}
componentWillUnmount() {
ProductsStore.removeChangeListener(this.changeListener);
}
I do not know, however, why this solves the issue. Any ideas?
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the exports component.
I am using the exact same implementation across multiple react components. i.e. this is repeated across several .jsx components.
componentDidMount: function() {
console.log('DidMount- Component 1');
ViewStateStore.addChangeListener(this._onChange);
},
componentWillUnmount: function() {
console.log('DidUnMount- Component 1');
ViewStateStore.removeChangeListener(this._onChange);
},
_onChange:function()
{
console.log('SetState- Component 1');
this.setState(getStateFromStores());
},
Possible Solution
Currently the following is working out for me, but it has been a little temperamental. Wrap the call back in a function/named-function.
ViewStateStore.addChangeListener(function (){this._onChange});
one might also try
ViewStateStore.addChangeListener(function named(){this._onChange});
Theory
EventEmitter is for some reason getting confused identifying the callback to remove. Using a named function is perhaps helping with that.
Try removing the .bind(this) from your addChangeListener and removeChangeListener. They are already bound to your component when they get called.
I decided it so
class Tooltip extends React.Component {
constructor (props) {
super(props);
this.state = {
handleOutsideClick: this.handleOutsideClick.bind(this)
};
}
componentDidMount () {
window.addEventListener('click', this.state.handleOutsideClick);
}
componentWillUnmount () {
window.removeEventListener('click', this.state.handleOutsideClick);
}
}
This is a es6 problem. React.createClass binds 'this' properly for all function defined inside its scope.
For es6, you have to do something yourself to bind the right 'this'. Calling bind(this) however, creates a new function each time, and passing its return value to removeChangeListener won't match the function passed into addChangeListener created by an earlier bind(this) call.
I see one solution here where bind(this) is called once for each function and the return value is saved and re-used later. That'll work fine. A more popular and slightly cleaner solution is using es6's arrow function.
componentDidMount() {
ProductsStore.addChangeListener(() => { this._onChange() });
}
componentWillUnmount() {
ProductsStore.removeChangeListener(() => { this._onChange());
}
Arrow functions capture the 'this' of the enclosing context without creating new functions each time. It's sort of designed for stuff like this.
As you already got to know the solution here, I will try to explain what's happening.
As per ES5 standard, we used to write following code to add and remove listener.
componentWillMount: function() {
BaseStore.addChangeListener("ON_API_SUCCESS", this._updateStore);
},
componentWillUnmount: function() {
BaseStore.removeChangeListener("ON_API_SUCCESS", this._updateStore);
}
In above code, memory reference for the callback function (ie: this._updateStore) is same. So, removeChangeListener will look for reference and will remove it.
Since, ES6 standard lacks autobinding this by default you have to bind this explicitly to the function.
Note: Bind method returns new reference for the callback.
Refer here for more info about bind
This is where problem occurs. When we do this._updateStore.bind(this), bind method returns new reference for that function. So, the reference that you have sent as an argument to addChangeListener is not same as the one in removeChangeListener method.
this._updateStore.bind(this) != this._updateStore.bind(this)
Solution:
There are two ways to solve this problem.
1. Store the event handler (ie: this._updateStore) in constructor as a member variable. (Your solution)
2. Create a custom changeListener function in store that will bind this for you. (Source: here)
Solution 1 explanation:
constructor (props) {
super(props);
/* Here we are binding "this" to _updateStore and storing
that inside _updateStoreHandler member */
this._updateStoreHandler = this._updateStore.bind(this);
/* Now we gonna user _updateStoreHandler's reference for
adding and removing change listener */
this.state = {
data: []
};
}
componentWillMount () {
/* Here we are using member "_updateStoreHandler" to add listener */
BaseStore.addChangeListener("ON_STORE_UPDATE", this._updateStoreHandler);
}
componentWillUnmount () {
/* Here we are using member "_updateStoreHandler" to remove listener */
BaseStore.removeChangeListener("ON_STORE_UPDATE", this._updateStoreHandler);
}
In above code, we are binding this to _updateStore function and assigning that to a member inside constructor. Later we are using that member to add and remove change listener.
Solution 2 explanation:
In this method, we modify BaseStore functionalities. Idea is to modify addChangeListener function in BaseStore to receive second argument this and inside that function we are binding this to the callback and storing that reference, so that while removing change listener we can remove with that reference.
You can find complete code gist here and source here.