【发布时间】:2021-12-12 22:15:27
【问题描述】:
我的 React 代码不起作用。
我有一个数组,对于每个项目,我需要渲染一张卡片。
但它不起作用。
这是所有代码:
const Home: NextPage = () => {
const [servers, setServers] = useState({});
async function getServers() {
console.log('ready');
const response = await fetch('http://localhost:3000/server/servers').then(
(res) => res.json()
);
setServers(response);
console.log(response);
console.log('servers object updated: ' + JSON.stringify(servers));
}
useEffect(() => {
getServers();
import('bootstrap/dist/js/bootstrap');
WebFont.load({
google: {
families: ['Karla:600', 'sans-serif'],
},
});
}, []);
useEffect(() => {
console.log('servers object updated: ' + JSON.stringify(servers));
}, [servers]);
return (
<div className="app">
<div className="container">
<div className="row" style={{ color: 'white' }}>
{servers.database?.map((server, index) => (
<div key={index} className="col">
<div
className="card"
style={{
width: '18rem',
backgroundColor: '#101114',
color: 'white',
marginTop: '80px',
borderRadius: '15px',
boxShadow: '4px 3px 5px 0px #7335fb',
}}
>
<img
src="https://cdn.discordapp.com/icons/843104500713127946/a_91371d39bec9e454d0f4ccacbfaea9f8.gif?size=512"
className="card-img-top"
alt="Icona server"
style={{
borderRadius: '50%',
width: '96px',
marginLeft: '20px',
marginTop: '60px',
}}
/>
<div className="card-body">
<h5 className="card-title">
{servers.bot[index].name || 'Errore!'}
</h5>
<br />
<p className="card-text">{server.shortDescription}</p>
<br />
<a
href="#"
className="btn"
style={{ backgroundColor: '#5316d9', color: 'white' }}
>
Entra
</a>
<a
href="#"
className="btn"
style={{
marginLeft: '10px',
backgroundColor: '#5316d9',
color: 'white',
}}
>
Visita
</a>
<br />
</div>
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default Home;
问题出在这里:
servers.database?.map((server, index) => (
<div key={index} className="col">
<div
className="card"
style={{
width: '18rem',
backgroundColor: '#101114',
color: 'white',
marginTop: '80px',
borderRadius: '15px',
boxShadow: '4px 3px 5px 0px #7335fb',
}}
>
<img
src="https://cdn.discordapp.com/icons/843104500713127946/a_91371d39bec9e454d0f4ccacbfaea9f8.gif?size=512"
className="card-img-top"
alt="Icona server"
style={{
borderRadius: '50%',
width: '96px',
marginLeft: '20px',
marginTop: '60px',
}}
/>
<div className="card-body">
<h5 className="card-title">{servers.bot[index].name || 'Errore!'}</h5>
<br />
<p className="card-text">{server.shortDescription}</p>
<br />
<a
href="#"
className="btn"
style={{ backgroundColor: '#5316d9', color: 'white' }}
>
Entra
</a>
<a
href="#"
className="btn"
style={{
marginLeft: '10px',
backgroundColor: '#5316d9',
color: 'white',
}}
>
Visita
</a>
<br />
</div>
</div>
</div>
));
有人知道为什么它不起作用吗?
没有错误,一切正常,但他不加载数组。
VScode 告诉我最初的 useState 值不包含必要的数据,但它是在之后从数据库到达的,所以我不在乎。
如果您有任何建议/解决方案,请告诉我。
提前致谢,对英语不好表示抱歉!
【问题讨论】:
-
您的 API 响应没有
.database属性。从 API 响应中找出您想要呈现的内容,并相应地导航对象。
标签: reactjs react-hooks use-state