我试图在我的反应组件中显示一个表格,但我不知道如何使用 useEffect 和 useState 在第一次渲染中渲染表格。
我的组件js:
import React, { useEffect, useState } from 'react'
const Projects = () => {
const [tableData, setTableData] = React.useState()
useEffect(() => {
fetch('https://script.google.com/macros/s/AKfycbzuKuSOUfd9IOsQobix0PnIRv28IB3uTx5KdpVoVeNe04g7QzXQeeCEbsHBxE5CYdEV8A/exec') //получение информации из API гугла
.then((response) => response.json()) //изменения формата в JSON
.then((response) => {
//запись значения JSON в переменную tableData
setTableData(response['smr'])
console.log('Response in useEffect:')
console.log(response['smr']) // data is OK
console.log('tableData in useEffect:')
console.log(tableData) // data is undefined
})
}, []);
return (
<div>
{/* {tableData.map(item => {
<div key={item.is}>
{item.adress}
</div>
})} */}
</div>
)
}
export default Projects
我还在 index.js 中使用路由:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>
);
只要你的请求成功完成,你就可以像这样有条件地渲染组件”
return (
<div>
{tableData && tableData.map(item =>
(<div key={item.is}>
{item.adress}
</div>)
)}
</div>
)
这样,组件仅在
tableData
不为假(即 null 或未定义)时呈现。