imperium2335 imperium2335 - 6 months ago 13
Javascript Question

ReactJS SetState not rerendering

I have:

JobScreen

handleSetView(mode, e) {
this.setState({
view: mode
});
console.log(this.state.view)
}

render() {
return (

<div className="jobs-screen">
<div className="col-xs-12 col-sm-10 job-list"><JobList view={this.state.view} /></div>
<div className="col-xs-12 col-sm-2 panel-container">
<div className="right-panel pull-right"><RightPanel handleSetView={this.handleSetView} /></div>
...
)
}


RightPanel

render() {
return (
<div>
<div className="controls">
<span className="title">Views <img src="images\ajax-loader-bar.gif" width="24" id="loader" className={this.state.loading ? "pull-right fadeIn" : "pull-right fadeOut"}/></span>
<button onClick={this.props.handleSetView.bind(this, 'expanded')}><img src="/images/icons/32px/libreoffice.png" /></button>
<button onClick={this.props.handleSetView.bind(this, 'condensed')}><img src="/images/icons/32px/stack.png" /></button>
</div>
...
)}


JobList

render() {
var jobs = [];
this.state.jobs.forEach((job) => {
jobs.push(
<Job key={job.id} job={job} view={this.props.view} loading={this.state.loading} toggleTraderModal={this.props.toggleTraderModal} toggleOFTModal={this.props.toggleOFTModal}/>
);
});

return (
<div>
{jobs}
</div>
);
};


The problem is, is that the changing of the view state does not rerender any of the child elements.

How can I get this to work?

Answer

Not sure if it is the core of your problem, but:

handleSetView={this.handleSetView}

is wrong, because how js binds this. Use:

handleSetView={this.handleSetView.bind(this)}

instead.

Also,

this.setState({
  view: mode
});
console.log(this.state.view)

seems strange; note that this.state is not modified right after you call setState, it may took some time while React dispatches the scheduled setState operation. Put that console.log into render to see when it is actually called.

Finally, make sure, your components do not implement shouldComponentUpdate lifecycle method (you are probably not doing this explicitly, but if your component extends some class other than React.Component this may happen)