在渲染反应钩子之前等待 API 调用数据

Kho*_*Phi 5 reactjs react-hooks

我进行了 API 调用。

看起来 React 继续构建一个没有数据的表,从而抛出错误

Uncaught TypeError: Cannot read property 'map' of undefined

这是我在做什么

useEffect() 很简单

  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();
  }, [])
Run Code Online (Sandbox Code Playgroud)

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

            <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>
Run Code Online (Sandbox Code Playgroud)

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

Ven*_*sky 5

您应该isBusyuseState初始值中设置为 true

//                            initial value
const [isBusy, setBusy] = useState(true)
Run Code Online (Sandbox Code Playgroud)

还要检查data之前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>
    )
})}
Run Code Online (Sandbox Code Playgroud)