如何解决无法在 Reactjs 中呈现数据
我是新来的,从昨天开始就一直在调试这个,我最终决定发帖,因为我对发生的事情一无所知。
以下反应代码从 api 获取数据,然后将其呈现在 UI 上。但是,这里很少发生奇怪的事情。
我最初收到错误说 TypeError: Cannot read property 'map' of undefined
,但是当我注释掉 {renderTableData(data)}
& save 然后再次取消注释并保存时,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>
</>
)
}
请提出解决方法
解决方法
如果你有数据,你只想运行这个函数,所以检查一下:
{data && renderTableData(data)}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。