为什么我不能在 reactjs 中从 .map 内部渲染组件?



我想显示一些基于使用fetch从api获得的数据的组件。当我尝试使用console.log调试它时,它有一个值,但组件不会显示。。我在这里做错了什么?

MasterRute.js

const MasterRute = () => {
const [rute, setRute] = useState([]);
useEffect(() => {
getRute();
}, []);
const getRute = async (query='') => {
const response = await fetch('http://localhost:8080/rute');
const data = await response.json();
setRute(data);
}
return (
<div>
{
rute.map((item, index) => {
if (index == 0) {
console.log(index, item.nama_rute); // 0 Lorem
(<div>{item.nama_rute}</div>)
}
})
}
</div>
);
}

非常感谢您的帮助

让我们分解一下这个返回语句:

return (
<div>
{
rute.map((item, index) => {
if (index == 0) {
console.log(index, item.nama_rute); // 0 Lorem
(<div>{item.nama_rute}</div>)
}
})
}
</div>
);

粗略地说,我们可以看到你正在返回"一个div元素,里面有一段JS";。这是";JS在您的div中":

rute.map((item, index) => {
if (index == 0) {
console.log(index, item.nama_rute); // 0 Lorem
(<div>{item.nama_rute}</div>)
}
})

现在让我们来分解一下。数组上有一个.map((,它应该接受一个函数,该函数接受(项,索引(并返回该项和索引的值。

但这真的发生了吗?

if (index == 0) {
console.log(index, item.nama_rute);
(<div>{item.nama_rute}</div>)
}

它正在记录值,但没有返回任何内容!则CCD_ 3也可以只是另一个CCD_。

试试这个:

if (index == 0) {
console.log(index, item.nama_rute);
return <div>{item.nama_rute}</div>;
} else {
return <div>Not supported yet</div>
}

希望这能有所帮助!

我不确定你是否可以在jsx中使用if语句,试试这个:

return (
<div>
{rute.map((item, index) => (<>{index === 0 && <div>{item.nama_rute}</div></>}))}
</div>
);

最新更新