【问题标题】:React Prop returning Null as it relies on stateReact Prop 返回 Null,因为它依赖于状态
【发布时间】:2022-07-05 16:45:34
【问题描述】:

希望是一个简单的。

我在我的组件中进行 API 调用,它会记录一些帐户信息,例如 AccountUid、Category 等,我使用状态来设置这些信息。

    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]);

这工作得很好,它在我的 .then 中记录正确的值。

然而,问题是我想将这些作为道具传递下去。但是我收到一个错误,它们被返回为 null(我的默认状态)。我假设它们正在向前跳跃。

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

如何将即时记录的 2 个详细信息作为道具传递?我已经尝试将默认状态设置为 "" 而不是 null 并且只是得到它是未定义的。

【问题讨论】:

  • 仅当accountDetails 不为空时,您能否有条件地呈现您的子组件?
  • 好吧,我真的不希望它有条件地渲染。子组件将始终呈现我只是不介意在调用时传递的详细信息是否为空白 0.2 秒。

标签: javascript reactjs components state react-props


【解决方案1】:

由于获取是异步的,最常见的方式是显示一些指示(如微调器),一旦数据进入,就显示组件。

查看react-query library exampleuseFetch hook 等更轻松的抽象,看看他们是如何管理它的

【讨论】:

    【解决方案2】:

    如果你不想在你的子组件中使用条件渲染,那么你应该尝试可选链接

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

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 2021-07-17
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多