[英]map is not a function in react js
Tried to map down this response but it was showing me an error even when i put in in a usestate
array.试图 map 降低此响应,但即使我放入
usestate
数组,它也向我显示错误。 Kindly go through my code to see if you can fix the error..请通过我的代码 go 看看您是否可以修复错误..
function Comment() {
const [comment_data, setcomment_data] = useState([]);
useEffect(() => {
const query = `
query{
forumAnswerId(id:1){
forumAnswerBody
forumAnswerTime
forumAnswerCode1
forumAnswerCode2
forumAnswerCode3
forumAnswerAuthor
forumAnswerBoolean
forumAnswerCode1Title
forumAnswerCode2Title
forumAnswerCode3Title
}
forumComment(forumAnswerComment:1){
forumAnswerCommentPost
forumAnswerCommentBody
forumAnswerCommentAuthor
forumAnswerCommentTime
}
}
`;
const opts = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query }),
};
const res = fetch('http://127.0.0.1:8000', opts)
.then((res) => res.json())
.then((r) => setcomment_data(r));
}, [])
const map = comment_data.map((e) => {
return (
<>
{comment_data.map((inner) => (
<>
{inner.data?.forumAnswerId?.map((data) => (
<></>
))}
</>
))}
</>
);
});
console.log(comment_data);
return (
<div>
{map}
</div>
);
}
API structure API结构
i have used a useEffect
hook to load in data and store the data in the state variable and access it.我使用
useEffect
挂钩加载数据并将数据存储在 state 变量中并访问它。
if I've well understood your api's reponse, what you're fetching is not an array.如果我很好地理解了您的 api 的响应,那么您获取的不是数组。 It's an object with a property
data
and that's what's in comment_data
.这是一个带有属性
data
的 object ,这就是comment_data
中的内容。 So no comment_data.map()
所以没有
comment_data.map()
The comment_data that you've console.logged and shared shows that comment_data is an object that contains the key "data".您 console.logged 和共享的 comment_data 表明 comment_data 是一个 object 包含键“数据”。
If you're looking to map all the keys for that object, you could do Object.keys(comment_data) and map that array and access values of keys like comment_data[key]. If you're looking to map all the keys for that object, you could do Object.keys(comment_data) and map that array and access values of keys like comment_data[key].
I think from the context of your code, you're looking for something like this:我认为从您的代码上下文来看,您正在寻找这样的东西:
const map = comment_data.data?.forumAnswerId?.map((data) => (<>{data.forumAnswerBody}</>))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.