父状态更改后,如何停止子组件功能再次运行?

时间:2019-05-21 05:24:32

标签: javascript reactjs

我有两个组件:App(父)和AddToCart(子)。在子组件中,我正在将子组件的整个状态添加到localStorage;然后我在将东西添加到localStorage时从孩子的父对象中调用一个函数,该函数检查localStorage项并更改父组件的状态。但是,问题在于父级状态更改后,它正在调用子级函数,该函数将相同的内容两次添加到localStorage。

我尝试将本地存储数据存储在父项的props中,但是它没有将prop值传递给其他子项。

这是AddToCart组件(子代)代码:

import React, { Component } from "react";

let cartItems = [];

export default class AddToCart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      one: ""
    };
  }

  updateCart = () => {
    this.setState(
      {
        one: "some value"
      },
      () => {
        this.props.checkCart();
      }
    );
  };

  componentDidUpdate() {
    this.populateStorage();
    console.log("function is being called twice");
  }

  populateStorage = () => {
    cartItems.push(this.state);
    localStorage.setItem("cart", JSON.stringify(cartItems));
  };

  render() {
    return (
      <React.Fragment>
        <button className="btn btn--white" onClick={this.updateCart}>
           Add to cart
        </button>
      </React.Fragment>
    );
  }
}

这是App组件(父)代码:


import React, { Component } from "react";

import Header from "./components/layouts/Header";
import AddToCart from "./components/AddToCart";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { cartCount: 0 };
  }

  handleCartCount = cart => {
    let count = cart.length;
    this.setState({ cartCount: count });
  };

  componentDidMount() {
    this.checkCart();
  }

  checkCart = () => {
    if (localStorage.getItem("cart")) {
      let cartStorage = JSON.parse(localStorage.getItem("cart"));
      return this.handleCartCount(cartStorage);
    } else {
      console.log("Cart is empty!");
    }
  };

  render() {
    return (
      <div className="App">
        <Header cartCount={this.state.cartCount} />
        <AddToCart checkCart={this.checkCart} />
      </div>
    );
  }
}

export default App;

有什么办法可以阻止子组件再次更新?谢谢。

1 个答案:

答案 0 :(得分:0)

首先,您不需要componentDidUpdate()。这将导致您在组件首次渲染后立即保存项目。

updateCart()设置setState后,请重新使用组件以在回调中使用this.populateStorage()

import React, { Component } from "react";

let cartItems = [];

Here's the sandbox for reference: https://codesandbox.io/s/black-sun-i4omf

    export default class AddToCart extends Component {
      constructor(props) {
        super(props);
        this.state = {
          one: ""
        };
      }

      updateCart = () => {
        this.setState(
          {
            one: "some value"
          },
          () => {
            this.populateStorage();
          }
        );
      };


      populateStorage = () => {
        cartItems.push(this.state);
        console.log(cartItems);
        localStorage.setItem("cart", JSON.stringify(cartItems));
      };

      render() {
        return (
          <React.Fragment>
            <button className="btn btn--white" onClick={this.updateCart}>
              Add to cart
            </button>
          </React.Fragment>
        );
      }
    }