在渲染反应钩子之前等待 API 调用数据 [英] Wait for API call data before render react hooks

查看:35
本文介绍了在渲染反应钩子之前等待 API 调用数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了 API 调用.

React 似乎在没有数据的情况下继续构建表,从而抛出

的错误

未捕获的类型错误:无法读取未定义的属性 'map'

这就是我在做的

useEffect() 非常简单

 const [data, setData] = useState();const [isBusy, setBusy] = useState()useEffect(() => {设置忙(真);异步函数 fetchData() {const url = `${process.env.REACT_APP_API_BASE}/api/v1/endpoint/`;axios.get(url).then((response: any) => {设置忙(假);设置数据(响应.数据.结果)控制台日志(响应.数据.结果);});}fetchData();}, [])

然后我尝试使用来自上述 API 调用的数据(当它可用时)呈现一个表格

 

{忙 ?(<装载机/>) : (<table className="table table-hover"><头><tr><th scope="col">药房用户全名</th><th scope="col">本月测试</th><th scope="col">本周测试</th><th scope="col">上次测试日期</th></tr></thead>{data.map((item: any, index: any) => {返回(<th scope="row" key={index}>{item.name}</th><td>标记</td><td>奥托</td><td>@mdo</td></tr>)})}</tbody>)}

以上对我来说足够直观.所以不确定我需要做什么.谢谢.

解决方案

您应该在 useState 初始值中将 isBusy 设置为 true

//初始值const [isBusy, setBusy] = useState(true)

并在data.map

之前检查data

//检查数据{数据&&data.map((item: any, index: any) => {返回(<th scope="row" key={index}>{item.name}</th><td>标记</td><td>奥托</td><td>@mdo</td></tr>)})}

I make an API call.

It appears React goes ahead to build a table without the data, thus throwing error of

Uncaught TypeError: Cannot read property 'map' of undefined

Here's what I'm doing

useEffect() pretty straightforward

  const [data, setData] = useState();
  const [isBusy, setBusy] = useState()

  useEffect(() => {
    setBusy(true);
    async function fetchData() {
      const url = `${
        process.env.REACT_APP_API_BASE
        }/api/v1/endpoint/`;

      axios.get(url).then((response: any) => {
        setBusy(false);
        setData(response.data.results)
        console.log(response.data.results);
      });
    }

    fetchData();
  }, [])

Then I'm trying to render a table using the data from the API call above (as and when it becomes available)

            <div className="col-md-12 mt-5">
              {isBusy ? (
                <Loader />
              ) : (
                  <table className="table table-hover">
                    <thead>
                      <tr>
                        <th scope="col">Pharmacy User Full Name</th>
                        <th scope="col">Tests This Month</th>
                        <th scope="col">Tests This Week</th>
                        <th scope="col">Last Test Date</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.map((item: any, index: any) => {
                        return (<tr>
                          <th scope="row" key={index}>{item.name}</th>
                          <td>Mark</td>
                          <td>Otto</td>
                          <td>@mdo</td>
                        </tr>
                        )
                      })}

                    </tbody>
                  </table>
                )}
            </div>

The above appears intuitive enough for me. So not sure what I need to do. Thanks.

解决方案

You should set isBusy to true in the useState initial value

//                            initial value
const [isBusy, setBusy] = useState(true)

And also check data before data.map

// checking data
{data && data.map((item: any, index: any) => {
    return (<tr>
      <th scope="row" key={index}>{item.name}</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    )
})}

这篇关于在渲染反应钩子之前等待 API 调用数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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