I want to fetch some values from a json file and render them in multiple components. This code doesn't seem to work. Please suggest any changes. probably there are some issues with scope.
var App = React.createClass({
getInitialState: function(){
return { myData: [] }
},
showResults: function(response){
this.setState(
{myData: response}
)
},
loadData: function(URL) {
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: URL,
success: function(response){
this.showResults(response)
}.bind(this)
})
},
render: function(){
this.loadData("fileLocation/sample.json");
return(
<div>
{myData.key1}
<Component1 value={myData.key2} />
<Component2 value={myData.array[0].key3}/>
</div>
)
}
});
var Component1 = React.createClass({
render: function () {
return(
<div>{this.props.value}</div>
)
}
});
var Component2 = React.createClass({
render: function () {
return(
<div>{this.props.value}</div>
)
}
});
ReactDOM.render(<App/>, document.getElementById('content'));
This is sample.json file I'm trying to fetch from. Even this shows a syntax error
{
key1:"value1",
key2:"value2",
array: [
{key3:"value3"},
{key4:"value4"}
]
}
myData.bethis.state.myData.?this.loadData()in thecomponentDidMountorcomponentWillMount. Else, it'll infinitely call due to state change..bind(this)is referring to the xhr object. Assign an alias tothisoutside the$.ajaxat the beginning ofloadDatafunction, and then utilize the alias at the success callback to refer to the actual this that you want.