繁体   English   中英

将状态保存到本地存储后无法设置状态

[英]Can't set state after saving it to local storage in React

我正在我的应用程序中实现搜索过滤器,并且需要在刷新浏览器之间保留数据。

这是我的代码:

    class App extends Component {
  state = {
    data: shop,
    direction: {
      price: "asc",
      title: "asc"
    },
    searchTitle: "",
    searchPrice: {
      min: null,
      max: null
    }
  };

  componentDidUpdate() {
    const state = {
      searchTitle: this.state.searchTitle,
      searchPrice: this.state.searchPrice,
      direction: this.state.direction
    };

    window.localStorage.setItem("saved_state", JSON.stringify(state));
  }

  componentDidMount() {
    const state = JSON.parse(window.localStorage.getItem("saved_state"));

    console.log(state);

    if (state) {
      this.setState({
        searchTitle: state.searchTitle,
        searchPrice: state.searchPrice,
        direction: state.direction
      });
    }
  }

  // PRICE SORT
  priceSort = key => {
    this.setState({
      data: shop.sort(
        this.state.direction[key] === "asc"
          ? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
          : (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
      ),
      direction: {
        [key]: this.state.direction[key] === "asc" ? "desc" : "asc"
      }
    });
  };

  // OLD PRICE SORT
  oldPriceSort = key => {
    this.setState({
      data: shop.sort(
        this.state.direction[key] === "asc"
          ? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
          : (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
      ),
      direction: {
        [key]: this.state.direction[key] === "asc" ? "desc" : "asc"
      }
    });
  };

  // TITLE SORT
  titleSort = key => {
    this.setState({
      data: shop.sort(
        this.state.direction[key] === "asc"
          ? (a, b) => a.data[key].localeCompare(b.data[key])
          : (a, b) => b.data[key].localeCompare(a.data[key])
      ),
      direction: {
        [key]: this.state.direction[key] === "asc" ? "desc" : "asc"
      }
    });
  };

  // TITLE FILTER
  updateTitleSearch = event => {
    this.setState({
      searchTitle: event.target.value
    });
    this.titleSearch();
  };

  titleSearch = () => {
    if (this.state.searchTitle) {
      this.setState({
        data: shop
          .filter(item => {
            return (
              item.data.title
                .toLowerCase()
                .indexOf(this.state.searchTitle.toLowerCase()) !== -1
            );
          })
          .sort(
            this.state.direction.title === "asc"
              ? (a, b) => a.data.title.localeCompare(b.data.title)
              : (a, b) => b.data.title.localeCompare(a.data.title)
          )
      });
    }
  };

  // PRICE FILTER
  updateMinSearchPrice = event => {
    this.setState({
      searchPrice: { ...this.state.searchPrice, min: event.target.value }
    });
  };

  updateMaxSearchPrice = event => {
    this.setState({
      searchPrice: { ...this.state.searchPrice, max: event.target.value }
    });
  };

  priceSearch = () => {
    if (this.state.searchPrice.min || this.state.searchPrice.max) {
      this.setState({
        data: shop
          .filter(item => {
            return (
              parseFloat(item.data.price) >= this.state.searchPrice.min &&
              parseFloat(item.data.price) <= this.state.searchPrice.max
            );
          })
          .sort(
            this.state.direction.price === "asc"
              ? (a, b) => parseFloat(a.data.price) - parseFloat(b.data.price)
              : (a, b) => parseFloat(b.data.price) - parseFloat(a.data.price)
          )
      });
    }

    if (!this.state.searchPrice.max) {
      this.setState({
        data: shop.filter(item => {
          return parseFloat(item.data.price) >= this.state.searchPrice.min;
        })
      });
    }
  };

  render() {
    return (
      <div className="page-container">
        <h1>Welcome to ShopMeNow!</h1>
        <Filters
          updateTitleSearch={this.updateTitleSearch}
          titleSearch={this.titleSearch}
          updateMinSearchPrice={this.updateMinSearchPrice}
          updateMaxSearchPrice={this.updateMaxSearchPrice}
          priceSearch={this.priceSearch}
        />
        <ItemTable
          data={this.state.data}
          priceSort={this.priceSort}
          oldPriceSort={this.oldPriceSort}
          titleSort={this.titleSort}
        />
      </div>
    );
  }
}

export default App;

我的目的是在componentDidMount()挂钩中获取保存的数据。 但这似乎不起作用(我已经尝试过用console.log记录它)

我要做什么才能使它继续进行? 谢谢社区!

而不是在ComponentDidMount中设置State,为什么不创建一个完全不同的函数,然后在ComponentDidMount中调用该函数。

所有设置状态代码都将添加到该功能中。 试试看,让我知道是否有效,干杯!

    ComponentDidMount(){ 

       this.changeValues();

   }

   changeValues(){

     const state = JSON.parse(window.localStorage.getItem("saved_state"));

    console.log(state);

    if (state) {
      this.setState({
        searchTitle: state.searchTitle,
        searchPrice: state.searchPrice,
        direction: state.direction
      });
    }

   }

我认为的问题是您正在将数据保存在componentDidUpdate的localStorage中,并且试图从componentDidMount的本地存储中获取数据。

您需要了解在componentDidUpdate之前调用的componentDidMount,这意味着您需要在设置之前从本地存储读取数据。

因此,您需要先设置数据,然后再读取数据

您在componentDidUpdate中这样做有什么特殊的原因吗? 如果没有,我建议将该功能移至单独的功能。 从事态发展目前情况看,任何更新,包括this.setState S于data ,你不希望保存到localStorage的。

也许您会考虑编写一个设置状态并将其保存到localStorage的函数,因为您的排序函数已经非常庞大。

样本伪代码:

setStateWithLocalStorage = newState => {
  const { searchTitle, searchPrice, direction } = this.state;
  this.setState(newState, () => {
      localStorage.setItem('saved_state', { searchTitle, searchPrice, direction })
  })
}

那么您可以在排序函数上使用此函数而不是this.setState

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM