仅将数据提取一次到React App.页面重新加载后再也不会获取 [英] Fetch data only once to React App. Never fetch again after page reloads

查看:47
本文介绍了仅将数据提取一次到React App.页面重新加载后再也不会获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能只向运行中的React应用获取一次数据. 我要实现的目标是: 我有一个应用程序,该应用程序是从JSONPLACEHOLDER API提取用户数据,然后将该数据传递到此组件的状态并分配给usersArray变量的.

I'm wondering if it's possible to fetch data only once to a running React app. The goal that I want to achieve is this: I have an app where I'm fetching user data from JSONPLACEHOLDER API, then passing this data to the state of this component and assigning to a usersArray variable.

在应用程序运行期间,进行了一些操作,例如从此usersArray删除数据.

During app is running there are some actions proceeded like deleting data from this usersArray.

发生了什么事

页面重新加载后,主要组件将再次安装,并且数据将再次获取.

After the page reloads, the main component is mounting once again and the data is fetched once again.

期望:

我只想永久获取一次此数据.是否有可能以某种方式在React中实现这一目标,或者我做错了什么?

I want to fetch this data only once and forever. Is it possible somehow to achieve this thing in React or I'm doing something wrong ?

推荐答案

您可以将数据放入

You could put the data in localStorage and always check if there is some data there before doing the request.

示例

class App extends React.Component {
  state = { users: [] };

  componentDidMount() {
    let users = localStorage.getItem("users");

    if (users) {
      users = JSON.parse(users);
      this.setState({ users });
    } else {
      fetch("https://jsonplaceholder.typicode.com/users")
        .then(res => res.json())
        .then(users => {
          this.setState({ users });
          localStorage.setItem("users", JSON.stringify(users));
        });
    }
  }

  handleClick = index => {
    this.setState(
      prevState => {
        const users = [...prevState.users];
        users.splice(index, 1);
        return { users };
      },
      () => {
        localStorage.setItem("users", JSON.stringify(this.state.users));
      }
    );
  };

  render() {
    return (
      <div>
        {this.state.users.map((user, index) => (
          <div key={user.id}>
            <span>{user.name}</span>
            <button onClick={() => this.handleClick(index)}>Remove</button>
          </div>
        ))}
      </div>
    );
  }
}

这篇关于仅将数据提取一次到React App.页面重新加载后再也不会获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆