简体   繁体   English

没有初始状态的 React 钩子

[英]React hooks without initial state

I am working on a project where I am fetching some data from an API and storing it as a JSON object in a state hook.我正在处理一个项目,我从 API 获取一些数据并将其作为 JSON 对象存储在状态挂钩中。 However, when initialised with const [data, setData] = useState([]) , obviously, data stores an initial value of [] before fetchAPI passes in the correct values, which is causing all sorts of problems on the functionality because my functions cannot work on empty objects.但是,当使用const [data, setData] = useState([])初始化时,显然, data在 fetchAPI 传入正确值之前存储了[]的初始值,这会导致功能上的各种问题,因为我的函数不能处理空物体。

I have tried sleep methods, async/await functions but it all comes down to me having to initialise that state.我尝试过 sleep 方法、async/await 函数,但这一切都归结为我必须初始化该状态。 Components look like this:组件如下所示:

// fetchHook.js

import React, { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  async function fetchUrl() {
    const response = await fetch(url);
    const json = await response.json();
    setData(json);
    setLoading(false);
  }

  useEffect(() => {
    fetchUrl();
  }, []);

  return [data, loading];
}

export { useFetch };

and it is imported on main App component which then passes the data as users to another component like so:并将其导入到主 App 组件上,然后将data作为用户传递给另一个组件,如下所示:

// App.js
import { useFetch } from "./components/fetchHook";


function App() {
  const [users, loading] = useFetch("https://api.github.com/users");

  return (
    <div className="App">
      <Profiles users={users} count={count} />
    </div>
  );
}

How can I make sure that fetch method always returns valid data before returning the initial state?如何确保 fetch 方法在返回初始状态之前始终返回有效数据?

Typical solution is to check error and loading and render appropriate:典型的解决方案是检查errorloading并进行适当的渲染:

  render() {
    return (
      loading ? <Loading/> :
      <div className="App">
        <Profiles users={users} count={count} />
      </div>
    )
  )

API typically return both error and loading status. API 通常返回错误和加载状态。 For example design of apollo return object with fields included names error and loading例如,带有字段的 apollo 返回对象的设计,包括名称errorloading

But in projects we can simplify as we like.但在项目中,我们可以随心所欲地简化。 For example we can return status field where both error an loading is packed:例如,我们可以返回状态字段,其中包含加载的两个错误:

  const [users, status] = useFetch("https://api.github.com/users");
  return status ? <Loading {...{status}}/> :
    <div className="App">
      <Profiles users={users} count={count} />
    </div>

Pretty much ideas about API design you can found in this discussion您可以在此讨论中找到有关 API 设计的很多想法

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

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