Im very new to ReactJs and wonder how I can set the initial state of a button component depending on the sql database data? I get the data via php & json and it works fine but I just can't get how to set the state. every tip is appreciated! Thanks
var OutfitList = React.createClass({
render: function() {
var outfitNodes = this.props.data.map(function (data) {
return (
<div className="col-xs-12 col-sm-12 col-md-6 col-lg-6 singleOutfit" style={{background: '#e5e5e5'}}>
<data author={data.author}>
<img src={data.url}/>
<div className='row subImage'>
<div className='col-xs-4 col-sm-4 col-md-4 col-lg-4'>
<div className={data.fav == 1 ? 'isFav btn' : 'btn'}>Click To Fav</div>
</div>
<div className='col-xs-4 col-sm-4 col-md-4 col-lg-4 text-center'><h4>{data.title}</h4></div>
<div className='col-xs-4 col-sm-4 col-md-4 col-lg-4'>{data.tags}</div>
</div>
</data>
</div>
);
});
return (
<div className="container">
<div className="row">
<h3>ALL</h3>
{outfitNodes}
</div>
</div>
);
}
});
var App = React.createClass({
loadOutfitsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadOutfitsFromServer();
setInterval(this.loadOutfitsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div>
<OutfitList data={this.props.data} />
</div>
);
}
});
React.render(
<App data={data} pollInterval={2000} />,
document.getElementById('content')
);
If you want to set some initial state use getInitialState()
. Whatever you return from this method is the initial state, which can thereafter be accessed with this.state.buttonState
and modified with this.setState()
.
Assuming your DB data is passed to this component as buttonState
, you can set state like this:
...
getInitialState: function() {
return {
buttonState: this.props.buttonState
}
}
render: function() {
return {
<div><button>this.state.buttonState</button></div>
}
}
...
However, for an example like this, consider not even setting any state because it creates a false source of truth . Instead, you could just use the passed in data from your DB directly in the button.
render: function() {
return {
<div><button>this.props.buttonState</button></div>
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.