【问题标题】:How to fetch Data and Update State with useState() useEffect() Hooks如何使用 useState() useEffect() Hooks 获取数据和更新状态
【发布时间】:2022-01-04 21:57:26
【问题描述】:

我尝试使用应该从 API 获取数据的 useEffect() 挂钩更新“提交”状态变量。但是在我执行setSubmissions(result.data) 然后将提交变量传递给Table 组件<Table data={submissions} /> 之后,它会导致错误TypeError: Cannot convert undefined or null to object,这告诉我我没有成功地将提交变量从API 获取更新为数组。

export default function Dashboard() {
    const [submissions, setSubmissions] = useState([]);
  
    useEffect(() => {
      async function loadData() {
        const query = `query {submissionsList {
           user_id type quantity impact date}
          }`;
        const response = await fetch ('http://localhost:8000/graphql', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json'},
          body: JSON.stringify({ query })
        });
        const result = await response.json()
        setSubmissions(result.data);
      }
      loadData();
    }, []);
  
    return (
        <Grid container spacing={4}>
          <Grid item xs={12}>
            <Widget>
              <Table data={submissions} />
            </Widget>
          </Grid>
        </Grid>)}

【问题讨论】:

  • 记录result 的结果是什么?在我看来,api 正在响应 undefined
  • @GhostOrder 出于某种原因,console.log 在useEffect() 挂钩之外工作,但不会在其中记录任何内容。
  • 你需要从useEffect内部console.log result,因为result在useEffect范围内,它不存在于它之外。
  • 同意,但由于某种原因,console.log 内的 useEffect 不起作用...
  • 您是否尝试记录其他数据(例如纯字符串)只是为了测试问题是否出在 console.log 上? (我对此表示怀疑,但以防万一),或者尝试记录result + 类似console.log('this is the result' + result) 的字符串。顺便说一句,react 是否会通知您一些错误?另一种可能性是您的服务器可能正在响应一个空字符串。

标签: reactjs react-hooks graphql use-effect use-state


【解决方案1】:

两件事 - 1) 对错误使用 try catch 块;和 2) 检查响应返回的内容

export default function Dashboard() {
const [submissions, setSubmissions] = useState([]);

useEffect(() => {
    async function loadData() {
        try {
            const query = `query {submissionsList {
            user_id type quantity impact date}
           }`;
            const response = await fetch('http://localhost:8000/graphql', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ query })
            });
            console.log(response);
            setSubmissions(response.data); // change this based on the response, you may or may not need to call json() on it

        } catch (error) {
            console.error(error);
        }
    }
    loadData();
}, []);

return (
    <Grid container spacing={4}>
        <Grid item xs={12}>
            <Widget>
                <Table data={submissions} />
                </Widget>
            </Grid>
        </Grid>
    );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2020-09-28
    • 2021-01-19
    • 2020-05-12
    • 1970-01-01
    • 2019-08-04
    • 2020-03-23
    相关资源
    最近更新 更多