【问题标题】:How to save state of React page on reload or redirecting back/ forward?如何在重新加载或重定向后退/前进时保存 React 页面的状态?
【发布时间】:2020-03-03 12:32:56
【问题描述】:

下面是我的代码。我正在使用 API 并在当前页面上获取一些数据。现在我想在重新加载页面或返回或再次前进时保存此页面的状态。

在这里,我从上一页 api 获取 featureGroupID 并将此处存储在全局变量 customerID 中。

我知道它是使用本地存储完成的,但由于我对 Reactjs 非常陌生,我不知道如何保存状态。有人可以帮忙吗?

class CustomerList extends Component {
  state = {
    isLoading: true,
    users: [],
    error: null,
    customerID: null
    };
    componentDidMount() {
      fetch('http://localhost:8080/entity/getEntityByFeatureGroup/'+this.customerID)
      .then(response => response.json())
      .then(data =>
       this.setState({
       users: data,
       isLoading: false,
    })
      ).catch(error => this.setState({ error, isLoading: false }));
	}
    render() {		
		var logTable = this.props;
		console.log(logTable);
      var customerColumnList = this.props;
      this.customerID = customerColumnList.location.aboutProps.id.featureGroupID;
      var headerName = customerColumnList.location.aboutProps.name.logTable.headerName;    
    const { isLoading, users, error } = this.state;
    return (....

【问题讨论】:

    标签: reactjs local-storage react-navigation react-props


    【解决方案1】:

    您可以使用localStorage.setItemlocalStorage.getItem 访问本地存储。喜欢:

    class CustomerList extends Component {
      state = {
        isLoading: true,
        users: [],
        error: null,
        customerID: null
        };
        componentDidMount() {
         if(!localStorage.getItem('customerlist-data')) {
            
    fetch('http://localhost:8080/entity/getEntityByFeatureGroup/'+this.customerID)
          .then(response => response.json())
          .then(data => {
           this.setState({
           users: data,
           isLoading: false,
        });
           localStorage.setItem('customerlist-data', data);
          }
          ).catch(error => this.setState({ error, isLoading: false }));
         enter code here}          
        }
        render() {      
            var logTable = this.props;
            console.log(logTable);
          var customerColumnList = this.props;
          this.customerID = customerColumnList.location.aboutProps.id.featureGroupID;
          var headerName = customerColumnList.location.aboutProps.name.logTable.headerName;    
        const { isLoading, users, error } = this.state;
        return (....

    【讨论】:

    • componetDidMount 中的 if 条件不起作用并给出错误
    【解决方案2】:

    可以存储数据+当前时间,有条件地取本地数据或再次从服务器获取。

    例如,我们可以决定,如果我们有数据存储在本地并且一个小时还没有过去,我们显示本地数据,否则我们从服务器获取。

    这是一个粗略的例子

    const storageKey = "myData";
    const toHour = ms => Number((ms / (1000 * 60 * 60)).toFixed(2));
    
    const storeDataLocally = data => {
      const dataObj = {
        date: Date.now(),
        data
      };
      localStorage.setItem(storageKey, JSON.stringify(dataObj));
    };
    
    const getDataLocally = () => {
      const dataObj = localStorage.getItem(storageKey);
      return JSON.parse(dataObj);
    };
    
    class App extends React.Component {
      state = {
        data: []
      };
    
      getDataFromServer = () => {
        console.log("from server");
        fetch("https://jsonplaceholder.typicode.com/users")
          .then(response => response.json())
          .then(data => {
            storeDataLocally(data);
            this.setState({ data });
          });
      };
    
      componentDidMount() {
        const localObj = getDataLocally();
        let shouldGetDataFromserver = false;
        if (localObj) {
          const isOneHourAgo =
            toHour(new Date()) - toHour(Number(localObj.date)) > 1;
          if (isOneHourAgo) {
            shouldGetDataFromserver = true;
          }
        } else {
          shouldGetDataFromserver = true;
        }
    
        shouldGetDataFromserver
          ? this.getDataFromServer()
          : this.setState({ data: localObj.data });
      }
    
      render() {
        const { data } = this.state;
        return (
          <div>
            {data.map(user => (
              <div key={user.id}>{user.name}</div>
            ))}
          </div>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-23
      • 2020-11-03
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 2013-02-12
      • 2015-12-17
      相关资源
      最近更新 更多