如何在重新加载或重定向后退/前进时保存React页面的状态?

问题描述 投票:0回答:2

下面是我的代码。我正在使用一个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
2个回答
0
投票

您可以使用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 (....

0
投票

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

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

这里是一个粗略的例子

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>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.