开发者问题收集

如何在 React js javascript 中映射给定的 api 响应

2021-06-10
430

当我在使用效果钩子中调用发布请求时出现错误,并且我得到的响应为承诺待定,但对象在那里,请查看响应并提供完美的代码来映​​射此响应。

在此处输入图像描述

代码

function Comment({ id }) {
    const [data, setdata] = useState([]);
    console.log(id);
    useEffect(() => {
        const query = `
    query{
      forumAnswerId(id:${id}){
        forumAnswerBody
        forumAnswerTime
        forumAnswerCode1
        forumAnswerCode2
        forumAnswerCode3
        forumAnswerAuthor
        forumAnswerBoolean
        forumAnswerCode1Title
        forumAnswerCode2Title
        forumAnswerCode3Title
      }
      forumComment(forumAnswerComment:${id}){
        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());

        setdata(res);
    }, []);
    return <div></div>;
}

export default Comment;
3个回答

您在这里:

fetch('http://127.0.0.1:8000', opts)
    .then((res) => res.json())
    .then(r=> setdata(r))
tuan nguyen
2021-06-10

promise 结果无法在外部访问。您需要在 then 函数内部设置数据

使用 Promise

fetch('http://127.0.0.1:8000', opts).then((res) => setdata(res.json()));

使用 Async await

const res=await fetch('http://127.0.0.1:8000', opts)
setdata(res.json())
Nithin K Joy
2021-06-10
useEffect(() => {
    const fetchData = async () => {
const query = `
query{
  forumAnswerId(id:${id}){
    forumAnswerBody
    forumAnswerTime
    forumAnswerCode1
    forumAnswerCode2
    forumAnswerCode3
    forumAnswerAuthor
    forumAnswerBoolean
    forumAnswerCode1Title
    forumAnswerCode2Title
    forumAnswerCode3Title
  }
  forumComment(forumAnswerComment:${id}){
    forumAnswerCommentPost
    forumAnswerCommentBody
    forumAnswerCommentAuthor
    forumAnswerCommentTime
    
  }
};`

const opts = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query }),
    };
    const res = await fetch('http://127.0.0.1:8000', opts).then((res) => res.json());

    setdata(res);
}

fetchData();

}, []);
Vivek Bani
2021-06-10