React Prop返回零,因为它依赖于状态

发布于 2025-02-13 00:24:00 字数 1381 浏览 4 评论 0 原文

希望只是一个。

我在我的组件中进行了一个API调用,其中带来了一些帐户信息,例如AccountUID,类别等,我使用状态设置这些信息。

    useEffect(() => {
    fetch(feed_url, {
      headers: {
        //Headers for avoiding CORS Error and Auth Token in a secure payload
        "Access-Control-Allow-Origin": "*",
        Authorization: process.env.REACT_APP_AUTH_TOKEN,
      },
    })
      //Return JSON if the Response is recieved
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        throw response;
      })
      //Set the Account Name state to the JSON data recieved
      .then((accountDetails) => {
        setAccountDetails(accountDetails);
        console.log(accountDetails.accounts[0].accountUid);
        console.log(accountDetails.accounts[0].defaultCategory);
      })
      //Log and Error Message if there is an issue in the Request
      .catch((error) => {
        console.error("Error fetching Transaction data: ", error);
      });
  }, [feed_url]);

这效果很好,并且在测试时记录了我的正确值。

但是,问题是我想将其作为道具传递。但是我遇到了一个错误,因为它们被返回为null(我的默认状态)。我想,他们跳下来。

    <div className="App">
  <GetAccountName
  accountUID={accountDetails.accounts[0].accountUID}
  defCategory={accountDetails.accounts[0].defaultCategory}
  />
</div>

我如何通过“道具”记录的两个细节来传递?我已经尝试将默认状态设置为“”而不是null,而只是确定它是未定义的。

Hopefully a simply one.

I make an API call in my component which brings down some account information such as AccountUid, Category etc, i use state to set these.

    useEffect(() => {
    fetch(feed_url, {
      headers: {
        //Headers for avoiding CORS Error and Auth Token in a secure payload
        "Access-Control-Allow-Origin": "*",
        Authorization: process.env.REACT_APP_AUTH_TOKEN,
      },
    })
      //Return JSON if the Response is recieved
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        throw response;
      })
      //Set the Account Name state to the JSON data recieved
      .then((accountDetails) => {
        setAccountDetails(accountDetails);
        console.log(accountDetails.accounts[0].accountUid);
        console.log(accountDetails.accounts[0].defaultCategory);
      })
      //Log and Error Message if there is an issue in the Request
      .catch((error) => {
        console.error("Error fetching Transaction data: ", error);
      });
  }, [feed_url]);

This Works perfectly well and it Logs the correct values in my .then when testing it.

The issue however is that i want to pass these down as props. But i get an error that they are being returned as null (My default state).. i presume as they're jumping ahead.

    <div className="App">
  <GetAccountName
  accountUID={accountDetails.accounts[0].accountUID}
  defCategory={accountDetails.accounts[0].defaultCategory}
  />
</div>

How do i pass the the 2 details im logging as props?? I've tried setting default state to "" instead of null and just get that it is undefined.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

む无字情书 2025-02-20 00:24:00

如果您不想在孩子组件中使用有条件渲染,因此应尝试可选的链接

<GetAccountName
  accountUID={accountDetails?.accounts?.[0]?.accountUID}
  defCategory={accountDetails?.accounts?.[0]?.defaultCategory}
/>

If you dont want to use conditional render in your child component, so you should try optional chaining

<GetAccountName
  accountUID={accountDetails?.accounts?.[0]?.accountUID}
  defCategory={accountDetails?.accounts?.[0]?.defaultCategory}
/>
白衬杉格子梦 2025-02-20 00:24:00

由于提取是异步的,因此最常见的方法是显示一些负载指示器(例如旋转器)&amp;数据进来后,请改用组件。

如果您不需要指标,则可能只需返回 null

一般的想法是根据承诺状态操纵某些中间状态(例如 data iSerror )。

查看或更轻的抽象(例如 usefetch hook 查看它们如何管理。

这是 usefetch 的示例实现>::

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [abort, setAbort] = React.useState(() => {});

  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const abortController = new AbortController();
        const signal = abortController.signal;
        setAbort(abortController.abort);
        const res = await fetch(url, {...options, signal});
        const json = await res.json();
        setResponse(json);
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
    return () => {
      abort();
    }
  }, []);

  return { response, error, abort };
};

Since fetching is asyncronous, the most common way is to show some loading indicator (like a spinner) & once the data come in, show the component instead.

If you don't need an indicator, you might just return null.

The general idea is to manipulate some intermediary states (e.g. data, isError) based on the promise state.

Check out react-query library example or a lighter abstraction like useFetch hook to see how they manage it.

Here's a sample implementation of useFetch taken from this article:

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [abort, setAbort] = React.useState(() => {});

  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const abortController = new AbortController();
        const signal = abortController.signal;
        setAbort(abortController.abort);
        const res = await fetch(url, {...options, signal});
        const json = await res.json();
        setResponse(json);
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
    return () => {
      abort();
    }
  }, []);

  return { response, error, abort };
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文