我已经使用react和redux编写了这段代码
class BooksContainer extends Component {
componentDidMount = () => {
const category = this.props.category;
this.props.searchBook(category);
this.props.fetchBook();
}
handleClickPrevious = () => {
console.log('clicked on previous: ' + this.props.previous)
this.props.urlprev(this.props.previous)
}
handleClickNext = () => {
console.log('clicked on next: ' + this.props.next)
this.props.urlnext(this.props.next)
}
render() {
const books = this.props.books;
let content = books
content = books.length > 0 ?
books.map(({ subjects, formats, title, authors }, index) => {
subjects = subjects.join()
if (subjects.includes('fiction') === true || subjects.includes('Fiction') === true) {
return (<div key={index} className="col-md-3 mb-5" >
<div className="card card-body bg-dark text-center h-100">
<img className="w-100 mb-2" src={formats['image/jpeg'] || close} alt="Book Cover" />
<h5 className="text-light text-left card-title">
{title}
</h5>
<p className="text-light text-left">
{authors.map(({ name }) => name)}
</p>
</div>
</div>)
}
}
)
: null;
return (
<div>
<div className="row">
{content}
</div>
<div>
<div className="d-flex justify-content-between">
<img className="bg-dark" src={left} alt="previous" onClick={this.handleClickPrevious} />
<img className="bg-dark" src={right} alt="next" onClick={this.handleClickNext} />
</div>
</div>
</div>
)
}
}
const mapStateToProps = state => ({
books: state.books.books,
next: state.books.next,
previous: state.books.previous
})
export default connect(mapStateToProps, { searchBook, fetchBook, urlprev, urlnext })(BooksContainer);
在return方法中,当我单击“下一个”或“上一个”时,它应从api Api-> http://skunkworks.ignitesol.com:8000/books提供的下一个链接中呈现书籍。 我想使用从下一个或上一个链接获得的书籍重新呈现相同的组件。 我尝试使用shouldComponentUpdate,但是如果我使用ShouldComponentUpdate则无法正常工作,那么当前显示的书籍也不会呈现
答案 0 :(得分:1)
您的组件将在属性或状态的任何依赖项更改时自动重新呈现,您也可以使用this.forceUpdate(),但这是极不推荐的。
鉴于您的组件已连接到Redux存储,调度动作来更改您当前选择的项目也会触发组件的重新渲染。我会在redux存储中将currentSelected作为变量,将其更改并通过mapStateToProps提取到我的组件中,然后可以使用操作来触发对currentSelected的更改,从而更新组件,从而有效地重新呈现它