javascript - 如何在 React Native 中使用 componentDidUpdate 和 shouldComponentUpdate?

标签 javascript reactjs react-native

我知道,如果 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();
        }
    }

最佳答案

您的问题不是shouldComponentUpdatecomponentDidUpdate

中是下面的比较
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/

相关文章:

android - 如果键盘打开,TouchableOpacity 的 onPress() 函数首先不起作用

javascript - 在客户网站上发现恶意代码

javascript - 如何使用react-google-maps从两个不同的SearchBoxes中获取formatted_address?

react-native - 返回按钮 react native 退出应用程序

javascript - 仅当不存在时才添加到 Realm 列表

javascript - React fetch polyfill 在移动设备上不起作用

javascript - HTML5 视频加载数据事件在 IOS Safari 中不起作用

javascript - jQuery onLoad 处理程序

javascript - 无法从js数组访问对象属性

javascript - React.js : project is not working