与strapi一起查看ID的元素信息,并进行反应
我正在学习与Strapi的反应。
我在数据库中有元素,我设法将它们显示为没有任何问题。
我希望当我们单击一个元素时,我们会看到该信息的信息。
因此,我在没有问题的情况下检索了链接ID,并设法显示信息,但只能使用一次。实际上,如果我单击第二个元素,则会有一个错误消息。
这是代码
const Articles = ({animal}) => {
const [error, setError] = useState(null);
const [Animaux, setAnimaux] = useState([]);
const { id } = useParams()
useEffect(() => {
axios
.get(`http://localhost:1337/api/animaux/`+id)
.then(({ data }) => setAnimaux(data))
.catch((error) => setError(error))
}, [id])
if (error) {
// Print errors if any
return <div>An error occured: {error.message}</div>;
}
console.log(Animaux)
return(
<div>
Id : {Animaux.data.id}
Nom : {Animaux.data.attributes.nom}
Description : {Animaux.data.attributes.Description}
<div key={animal.id} className="card" >
<span className="btn btn-primary">Voir {animal.attributes.nom}</span>
</div>
)}
*/}
</div>
)
};
导出默认文章;
这是第一次的结果: 这是我首次
我看到它返回了我一个空的数组,但我不明白为什么
很多很多感谢所有未来的帮助。
I'm learning react with strapi.
I have elements in a database and I manage to display them all without any problem.
I would like that when we click on an element we see the information of this one.
So I retrieve the link id without problem and I manage to display the information except that it only works once. In fact, if I click on the second element I have an error message.
Here is the code
const Articles = ({animal}) => {
const [error, setError] = useState(null);
const [Animaux, setAnimaux] = useState([]);
const { id } = useParams()
useEffect(() => {
axios
.get(`http://localhost:1337/api/animaux/`+id)
.then(({ data }) => setAnimaux(data))
.catch((error) => setError(error))
}, [id])
if (error) {
// Print errors if any
return <div>An error occured: {error.message}</div>;
}
console.log(Animaux)
return(
<div>
Id : {Animaux.data.id}
Nom : {Animaux.data.attributes.nom}
Description : {Animaux.data.attributes.Description}
<div key={animal.id} className="card" >
<span className="btn btn-primary">Voir {animal.attributes.nom}</span>
</div>
)}
*/}
</div>
)
};
export default Articles;
Here is the result the first time :
Here is the result the first time
The result that I have afterwards (after updating, then it does not come back at all)
The result after
I see that it returns me an empty array but I don't understand why
Many thanks to all for your future help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您从API获得的数据返回空数组。此外,如果不给出索引,您将无法访问数组的对象。
您不能像那样使用{animaux.data.id},您可以使用地图返回;
Data which you get from api returns empty array. In addition, you cannot access the object of the array without giving an index.
You can't use like that {Animaux.data.id}, you can return with map ;
您可以尝试使用可选的链式操作员吗?
Can you trying using the optional chaining operator.