无法在Reactjs中呈现数据 [英] Unable to render data in Reactjs

查看:59
本文介绍了无法在Reactjs中呈现数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的反应者,从昨天开始一直对此进行调试,由于对所发生的事情一无所知,我最终决定发布.

I am new to react and have been debugging this from yesterday and I finally decide to post as I am clueless of what is happening.

以下反应代码从api获取数据,然后将其呈现在UI上.但是,这里很少发生奇怪的事情.

The following react code fetches data from the api and then renders it on the UI. But, there are few strange things happening here.

我收到错误消息,表示为 TypeError:最初无法读取未定义的属性'map',但是当我注释掉 {renderTableData(data)} &保存,然后再次取消注释&保存,数据可以完美地呈现在用户界面上

I get error saying as TypeError: Cannot read property 'map' of undefined initially but when I comment out {renderTableData(data)}& save and then again uncomment & save, the data is rendering perfectly on the UI

我在想,甚至在从API提取数据之前,它都会传递给函数 renderTableData ,这就是为什么在控制台中打印 undefined 的原因.

I am thinking that before even the data gets fetched from API, it is getting passed to the function renderTableData which is why in the console undefined is printed.

这是代码

export default function TenantList(){
  const [data, setData] = useState([]);
    useEffect(() => {
      fetch('https://jsonplaceholder.typicode.com/users').then((response)=>{
        return response.json();
      }).then((data)=>{
        setData(data)
      })
    },[]);
 
function renderTableData(data) {
  console.log("hello ", data)
  return data.map((student, index) => {
      const { name, email } = student //destructuring
      return (
          <tr key={name}>
              <td>{name}</td>
              <td>{email}</td>
          </tr>
      )
  })
}
  return (
    <>
      <div>
        {renderTableData(data)}
      </div>
    </>
  )
}

请提出解决方法

推荐答案

如果仅具有数据,则只想运行此函数,因此请检查它:

You only want to run this function if you have the data, so check for it:

{data && renderTableData(data)}

这篇关于无法在Reactjs中呈现数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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