Reputation: 73
I need help with React.js.
I have a React Component called ContactsApp, this component call the method componentDidMount() that containts an Ajax Call with recieve props.
componentDidMount(){
jQuery("document").ready(function(){
jQuery("#sent-btn").click(function(ev){
var data_json = {};
data_json['word'] = jQuery("#word").val();
data_json['route'] = jQuery("#route").val();
console.log(data_json['word']);
console.log(data_json['route']);
$.ajax({
type: 'post',
url: 'logic',
data: JSON.stringify(data_json),
contentType: "application/json; charset=utf-8",
traditional: true,
}).then(function(data){
console.log(data);
var list = []
for (var i = 0; i < data.Data.length; i++) {
list.push({"name":data.Data[i].File , "email":data.Data[i].Quantity})
}
this.setState({contacts:list});
}.bind(this))
});
});
}
But my problem is these errors that the web console response for me.
1) Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
2) Uncaught TypeError: this.setState is not a function
The class is:
- Container
- ContactsApp
- SearchBar
- ContactList
- ContactItem
Finally I call render method with:
render(<ContactsAppContainer />, document.getElementById('forms'));
I have seen that someone people uses React History, but Cassio Zen don't use this and I think I'm okay.
My import libraries:
import React, { Component, PropTypes } from 'react';
import { render } from 'react-dom';
import 'whatwg-fetch';
import jQuery from 'jquery';
I was using a example based on React component by Cassio Zen.
Sorry my english, I'm learning this, please help me.
Upvotes: 0
Views: 319
Reputation: 29989
You're rebinding the context for this
inside your AJAX callback, but you've already lost the component's context as soon as you enter the jQuery ready
and click
callbacks.
It seems like you're using ES6, so the simple fix would be to use arrow functions instead.
componentDidMount() {
jQuery("document").ready(() => {
jQuery("#sent-btn").click(ev => {
// ...
$.ajax({
// ....
}).then(data => {
// ...
this.setState({contacts:list});
});
});
});
}
However it looks like you've got bigger problems with the other error. I'm not exactly sure what's causing it, but I'm confident that all the while you use jQuery inside your React components, you'll be making everything difficult for yourself.
Honestly, I'd go back a few steps and try and get a better sense of how to use event handlers to listen for button clicks and input changes with React, not with jQuery. Then remove the jQuery dependency from your application and switch the DOM code over to use React and use switch the AJAX code over to using fetch.
Upvotes: 2