【问题标题】:using 'Unstated' with React Js for fetching data from API endpoint使用带有 React Js 的“Unstated”从 API 端点获取数据
【发布时间】:2021-04-10 04:00:11
【问题描述】:

我已经开发了一个从 openweathermap.org 获取天气数据的应用程序。该应用程序是使用 redux 和 redux-saga 构建的。 现在我必须使用“Unstated”而不是 Redux 来重做状态管理。

WeatherContainer.js 类处理状态:

class WeatherContainer extends Container {
  state = { weather: [] };
  setWeatherData = (weather) => {
    this.setState({ ...this.state, weather });
  };
}

从 API 端点获取数据的 axios 请求。

axios.get(process.env.REACT_APP_BASE_URL, {
    params: {
      id: cityIds,
      units: "metric",
      appid: process.env.REACT_APP_API_KEY,
    },
  });

我想将从 axios 接收到的数据存储在 WeatherContainer 中的 state.weather 变量中,然后可以在需要时使用。

【问题讨论】:

    标签: reactjs axios state setstate unstated


    【解决方案1】:

    我搬到 unstated-next 来做 react js。带有反应钩子和所有的同一个库。使用 useState 钩子可以轻松管理状态,并且也可以应用所有反应钩子。 Link to github repo of unstated-next

    由于它是 React 上下文 API 的包装器,因此该库是轻量级的,不需要像 redux 那样的太多配置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 2019-01-05
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多