Reputation: 937
Why isn't mu render
method called when state is changed? I want to show the next image on next button click and the previous image on previous button click, but my render
method is not called when I update state. Here's a live demo.
I updated state like this:
next(){
var current = this.state.currentSlide;
var next = current + 1;
if (next > this.props.stories.items.length - 1) {
next = 0;
}
this.state.currentSlide = next;
console.log(this.state.currentSlide ,"next---")
}
pre(){
var current = this.state.currentSlide;
var prev = current - 1;
if (prev < 0) {
prev = this.props.stories.items.length - 1;
}
this.state.currentSlide = prev;
console.log(this.state.currentSlide ,"pre---")
}
Here's my render
method:
render() {
return (
<div>
<div className="imageSlider">
<ul>
{this.renderStories()}
</ul>
</div>
<button onClick={this.next}>next image</button>
<button
onClick={this.pre}>pre image</button>
</div>
);
Upvotes: 0
Views: 46
Reputation: 57944
Never, ever, mutate properties of the state
object outside of the constructor. Mutation of an object such as state leads to a whole bunch of issues and is the source of all evil. Use setState
to set the state:
this.setState({
currentSlide: next
});
Per Using State Correctly at the React docs:
Do Not Modify State Directly
For example, this will not re-render a component:
// Wrong this.state.comment = 'Hello';
Instead, use
setState()
:// Correct this.setState({comment: 'Hello'});
The only place where you can assign
this.state
is the constructor.
Upvotes: 2