【问题标题】:Unable to render data in Reactjs无法在 Reactjs 中呈现数据
【发布时间】:2020-12-22 20:20:47
【问题描述】:

我是新手,从昨天开始一直在调试这个问题,我最终决定发布,因为我对正在发生的事情一无所知。

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

我最初收到错误消息TypeError: Cannot read property 'map' of undefined,但是当我注释掉{renderTableData(data)}并保存然后再次取消注释并保存时,the data is rendering perfectly on the UI

我在想,在从 API 获取数据之前,它会被传递给函数 renderTableData,这就是为什么在控制台中打印 undefined

这里是代码

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>
    </>
  )
}

请提出解决方法

【问题讨论】:

  • 尝试在setData(data) 行之前的useEffect 中添加console.log(data),并告诉我它记录了什么。
  • 如果你有useState([]);,那么它不应该发生,因为data的初始值是一个数组。
  • @aryanm 我在 setData 之前写过console.log(data),但没有打印出来
  • 当然,你也可以给参数一个默认值,比如function renderTableData(data = []) {
  • 它不会等待(现在也不会等待),但是如果传递的参数是undefined,它将变为[],这意味着map将可用。

标签: reactjs react-hooks fetch-api


【解决方案1】:

如果你有数据,你只想运行这个函数,所以检查一下:

{data && renderTableData(data)}

【讨论】:

  • 非常感谢你 :) 我真的坐了好几个小时才解决这个问题。你是救世主
  • 接受。接受答案是有时间限制的,所以到现在都做不到
猜你喜欢
  • 2021-05-02
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 2017-02-01
  • 2022-01-16
相关资源
最近更新 更多