在从 GET 请求填充数组之前反应渲染

时间:2021-06-23 14:04:28

标签: javascript reactjs

我是 React 的新手,所以也欢迎指点。

我正在用 api 调用的 json 填充一个数组:

fetch('/rpa').then(rpa => rpa.json()).then(data => data.rpa).then(nestedData=>nestedData.forEach(item => jsonRespnse.push(item)));
console.log(jsonRespnse)

登录到控制台会显示我所期望的数据。但是,将这些数据作为回报的一部分,我什么也没得到:

  return (
        <div>
                {rpaName.map((rpaItem, i) => (
                <div>
                <div className='headerContainer' onClick={()=>toggle(i)}>
                <h4 className='rpaHeader'>{rpaItem}</h4><span className='rpaSpan'>{selected === i ? '-': '+'}</span>
                </div>
                <div className={selected === i ? 'rpaButton show': 'rpaButton'}>
                <button onClick={()=>sendData(rpaItem)}>Start{rpaItem}</button><button>Stop{rpaItem}</button>
                </div>
                <br></br>
                </div>))}
        </div>);}

我假设它是一个计时问题,在填充数组之前进行渲染,当我对数组进行硬编码时它工作正常。

如果有人能指出我正确的方向,我将不胜感激。

5 个答案:

答案 0 :(得分:2)

由于您使用的是函数式组件,因此您可以使用 react 的 useEffect 钩子在呈现组件之前执行 API 调用。

然后您可以使用 useState 钩子声明一个状态变量来保存获取的数据。

示例代码:

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

const yourComponent = () => {
   const [ data, setData ] = useState([]);

   useEffect(() => {
     fetch('<URL>').then(response => response.json()).then(responseArr => setData(responseArr)));
   }, []);

   return(
    //Rest of the code (Now you can use the fetched data as an array since "data" state's been populated with the data fetched from the API call)
   );
}

答案 1 :(得分:2)

使组件在其内部重新呈现的唯一方法是使用 state

在 React 世界中,由于您没有提供完整的组件,我假设您使用的是函数式组件,其中有诸如 useState 和 useEffect 之类的钩子。

useState 是您放置更改变量的位置。

示例。


function MyComponent() {
   // the first variable here is the actual value of the state, the next is the function to change the state.
   const [myState, setMyState] = React.useState(); 

   // when we move over to useEffect, is the hook that'd typically use to perform fetch requests for example. 

   React.useEffect(() => {
       fetch(...).then(response => response.json()).then(setMyState);
   }, [])

   return <div>{myState}</div>
}

当状态获得新值时,它会重新渲染组件以反映新的变化。

答案 2 :(得分:1)

您可能希望将请求数组设置为状态对象,例如

import React, { useState } from 'react';

function someReactComponent() {
  // Declare a new state variable, which we'll call "count"
  const [fetchResponse, setFetchResponse] = useState([]);

  fetch('/yourfetchurl').then(response => response.json()).then(responseArr => setFetchResponse(responseArr)));
  
  return (
    <div>
      {fetchResponse.map((res, i) => {
        return (
          <div key={i}>
            {res.whatever}
          </div>
        );
      })}
    </div>
  );
}

答案 3 :(得分:1)

感谢大家的回复 - 我真的设法将所有回复结合在一起,非常感谢。

一旦我在那里得到了 useState + useEffect 组合,这只是 JSON 如何被放入数组的一个例子,这就是给我错误的原因,我必须首先访问它们的键:

getList().then(items => setRpaList(items.rpa));

感谢您的帮助。

答案 4 :(得分:0)

您将需要一个 useEffect 在您的组件中进行网络调用,以便它在渲染后获取数据,以及一个 useState 来绑定变量数据。然后,一旦异步调用解决(即在回调中),使用结果数据调用状态设置器函数以刷新页面上的数据。

这篇文章提供了很好的解释:https://www.digitalocean.com/community/tutorials/how-to-call-web-apis-with-the-useeffect-hook-in-react

您还可以在渲染时启动微调器,并在获取回调运行后终止微调器。

请注意,console.log 不保证它会记录执行语句时的数据,这意味着运行该行时的 jsonResponse 可能是(在这种情况下, 它) 与您在控制台中观察到的输出不同。

相关问题