Reputation: 8551
I have a component which I have passed a property from another component.
As following <RegisterVisitor someProperty={this.aFunction} />
In the child component however this.props
is undefined outside of the constructor.
I took out the snippet of the code. this.props
is defined in render ()
but it is not defined registerVisitor
. Anyone know what the problem could be?
export default class RegisterVisitor extends React.Component {
constructor(props) {
super(props);
this.registerVisitor = this.registerVisitor.bind(this);
}
registerVisitor () {
$.ajax({
url: '/api/visit',
type: 'POST',
data: postData,
contentType: 'application/json'
})
.done(
function(result) {
this.props.someProperty; //<------ undefined
}
);
}
}
Upvotes: 1
Views: 407
Reputation: 77482
In .done
callback this
does not refer to RegisterVisitor
, you should set this
for callback., you can do it with .bind
...
.done(
function(result) {
this.props.someProperty;
}.bind(this)
);
or also you can use arrow function
...
.done((result) => {
this.props.someProperty;
});
Upvotes: 3