javascript - Get initial state of ReactJs button from database -
im new reactjs , wonder how can set initial state of button component depending on sql database data? data via php & json , works fine can't how set state. every tip 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 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 want set initial state use getinitialstate()
. whatever return method initial state, can thereafter accessed this.state.buttonstate
, modified this.setstate()
.
assuming db data passed component buttonstate
, can set state this:
... getinitialstate: function() { return { buttonstate: this.props.buttonstate } } render: function() { return { <div><button>this.state.buttonstate</button></div> } } ...
however, example this, consider not setting state because creates false source of truth. instead, use passed in data db directly in button.
render: function() { return { <div><button>this.props.buttonstate</button></div> } }
Comments
Post a Comment