为什么状态改变时没有调用 mu render
方法?我想在下一个按钮单击时显示下一个图像,在上一个按钮单击时显示上一个图像,但是当我更新状态时,不会调用我的 render
方法。这是a live demo .
我像这样更新了状态:
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---")
}
这是我的渲染
方法:
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>
);
最佳答案
永远不要在构造函数之外改变 state
对象的属性。诸如状态之类的对象的突变会导致一系列问题,并且是万恶之源。使用setState
设置状态:
this.setState({
currentSlide: next
});
每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.
关于javascript - 为什么我的组件没有在状态更改时重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45260634/