我知道,如果 shouldComponentUpdate 返回真,componentDidUpdate 将运行。在我的例子中,我在 chrome 调试器 session 中遇到无限循环。这可能导致性能低下。我的主要问题是,如何实际使用 componentDidUpdate??
state = {
cartItems: []
}
componentDidMount() {
this.getCart();
}
getCart = async () => {
let cart = await API.getCart();
if (cart) {
this.setState({
loading: false,
cartItems: cart
})
}
console.log(cart) //for checking it in chrome debugger
}
shouldComponentUpdate(prevProps, prevState) {
return prevState.cartItems != this.state.cartItems
}
componentDidUpdate(prevProps, prevState) {
if (prevState.cartItems != this.state.cartItems) {
this.getCart();
}
}
最佳答案
您的问题不是shouldComponentUpdate
。 componentDidUpdate
componentDidUpdate(prevProps, prevState) {
if (prevState.cartItems != this.state.cartItems) {
this.getCart();
}
}
由于数组的比较方式,这将始终为 true
,如果您将它与 !==
一起使用(这是推荐的方式),则比较将始终评估为 true
。
- 在
componentDidUpdate
中调用getCart
导致组件更新 - 在
componentDidUpdate
中,您再次调用getCart
,导致组件更新,再次调用getCart
等等。
要么对 cartItems
的每个项目执行深度比较
,要么检查 length
属性(在某些情况下可能有效)。或者,如果顺序无关紧要,您可以使用 JSON.stringify
componentDidUpdate(prevProps, prevState) {
if (JSON.stringify(prevState.cartItems) !== JSON.stringify(this.state.cartItems)) {
this.getCart();
}
}
要实现预期的行为(每次将项目添加到 cartItems
时重新获取,您可以执行以下操作
class Cart extends React.Component{
state = {
items : []
}
componentDidMount(){
getCart()
}
addItem = item =>{
this.setState(prevState => ({
items : prevState.items.concat(item)}
), this.getCart)
}
render(){
return <button onClick={() => this.addItem('item')}>Add</button>
}
}
通过使用 setState
的第二个参数,您可以确保 state
中的更改全部完成,一旦添加了 item
组件将再次获取,但这次没有循环
关于javascript - 如何在 React Native 中使用 componentDidUpdate 和 shouldComponentUpdate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807245/