我有一个react组件,它会显示一个封面列表和一个按钮,用于从onClick列表中删除该书 . 我将删除操作通过 Map 调度传递给道具,书架信息通过 Map 状态传递给道具 . 删除操作已成功从数据库中删除该书,并且正在击中我的reducer . 但即使状态更新,书籍列表组件也不会重新呈现(除非我重新加载,否则删除的书籍不会消失) .
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import {CarouselProvider, Slider, Slide, ButtonBack, ButtonNext, Image, Dot} from 'pure-react-carousel';
class BookshelfIndexItem extends React.Component {
constructor(props){
super(props);
}
render() {
return(
<div>
<h3 className='shelf-title'>{this.props.bookshelf.name}</h3>
<CarouselProvider
naturalSlideWidth={135}
naturalSlideHeight={250}
totalSlides={this.props.bookshelf.book_ids.length}
visibleSlides={3}>
<Slider style={{height: '240px', display: 'flex', 'justifyContent': 'space-between'}}>
{this.props.bookshelf.book_ids.map((id, index) =>(<Slide index={index}
key={id} style={{'width': '150px','display': 'flex','alignItems': 'center', 'margin': '0 50px'}}>
<Link to={`/books/${id}`}>
<Image style={{height: '200px', width: '140px'}} src ={this.props.books[id].image_url}></Image>
</Link>
<button style={{height: '35px', 'marginLeft': '55px', 'marginTop': '5px'}}
onClick={() => this.props.deleteBookFromBookshelf({book_id: id, bookshelf_id: this.props.bookshelf.id})}>
X
</button>
</Slide>))}
</Slider>
<div className='slider-button-container'>
<ButtonBack className='slider-button'>back</ButtonBack>
<ButtonNext className='slider-button'>next</ButtonNext>
</div>
</CarouselProvider>
</div>
);
}
}
export default withRouter(BookshelfIndexItem);
我已经尝试了一些生命周期方法,例如在ComponentWillReceiveProps中获取所有书架,但没有变化 .
1 回答
我有一种强烈的怀疑,我知道's up - any chance you'正在推送一个新列表的数组副本,它看到旧列表,看到新列表,并说“嘿,那些是内存中的同一个对象,所以既然're the same I don' t甚至需要触发
shouldComponentUpdate
.我已经生成了这种行为的最小示例,因此您可以看到它的实际效果:https://codesandbox.io/s/nrk07xx82j
如果你点击第一个按钮,你可以在控制台中看到新状态实际上是正确的,但渲染列表永远不会更新(因为我上面讨论过) .
但是,如果使用数组解构(
[...list]
),最终会返回相同的数组内容,但在新的数组对象中,会触发React更新 .希望有所帮助!
忍者编辑:意识到我可能更具体,因为你正在谈论删除项目 -
Array.pop
和Array.splice()
两者都以相同的方式行事,你're still dealing with the same object in memory and thus won'触发组件更新 .