javascript - componentDidMount 同步更新

标签 javascript reactjs

我正在使用以下方式从保存的 session 中加载数据:

componentDidMount() {
    if (JSON.parse(localStorage.getItem('savedData')) !== null) {
        this.setState({
            cartItems: JSON.parse(localStorage.getItem('savedData')),
            totalPrice: this.getPriceOnLoad(),
            totalItems: this.getItemsOnLoad(),
        });
    }
}

cartItems 是一个对象数组。哪个好像之前更新过

this.getPriceOnLoad();
this.getItemsOnLoad();

函数被调用,例如this.getPriceOnLoad函数:

getPriceOnLoad() {
    let itemsPrice = 0;
    for (let i = 0; i <= this.state.cartItems.length - 1; i++) {
        itemsPrice += this.state.cartItems[i].quantity * this.state.cartItems[i].price;
    }
    return itemsPrice;
}

但是,在getPriceOnLoad函数中,this.state.cartItems.length等于0,所以for循环没有执行。我可以在 React 开发工具中看到这个数组有一定的长度。是因为 componentDidMount() 正在同步执行状态变化,不能立即看到更新的数组吗?所以我的问题是如何在数组初始化后更新商品的价格和数量?

最佳答案

您的状态未按顺序更新。为此,您可以将 cartItems 存储在一个临时值中,并将其发送到每个函数:

componentDidMount() {
    if (JSON.parse(localStorage.getItem('savedData')) !== null) {
        const cartItems = JSON.parse(localStorage.getItem('savedData'))
        this.setState({
            cartItems, //Short syntax for 'cartItems: cartItems'
            totalPrice: this.getPriceOnLoad(cartItems),
            totalItems: this.getItemsOnLoad(cartItems),
        });
    }
}

您还可以使用 reduce 显着缩短您的函数:

this.setState({
    cartItems,
    totalPrice: cartItems.reduce((total, item) => total + (item.quantity * item.price), 0),
    totalItems: cartItems.reduce((total, item) => total + item.quantity, 0),
});

您也可以向我们展示您的第二个功能吗?它也可能被优化。 完成。

关于javascript - componentDidMount 同步更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54292698/

相关文章:

javascript - Google App Maker 中的嵌入式 map 无法在 Chrome 浏览器中呈现

javascript - create-react-app 排除文件夹触发重新加载

javascript - iPad 上的 jQuery 单击事件无法正常工作

javascript - React应用程序中src文件夹的Webpack别名?

javascript - 自从更新react-dom和react-router-dom包: behaviors executing additional times

javascript - 为什么这两个相同的字符串在JavaScript中不相等?

javascript - 机器人未定义不和谐机器人

javascript - React.js——如何将属性对象传递给子组件?

javascript - react :Uncaught TypeError: Cannot read property 'set' of undefined

css - 用于列的 Antd 响应式 Flex