Reactjs useState 挂钩不更新承诺数据

Reactjs useState hook not updating on promise data

我正在使用 React Hook 而不是基于 class 的组件,但是当我从 graphql API.

获取数据时它没有更新状态

这是我的代码:

import React, { useEffect, useState } from 'react';
import client from '../gqlClient';
import { gql, ApolloClient, InMemoryCache  } from '@apollo/client';


const client = new ApolloClient({
  uri: 'http://localhost:8000/graphql/',
  cache: new InMemoryCache(),
});


function EmpTable() {

  const [employee, setEmployee] = useState({});

    useEffect(() => {

        client
            .query({
                query: gql`
                query {
                  employees {
                    name
                  }
                }
                `
            })
            .then(result => {
              setEmployee({result});
              console.log(employee);
            });
    }, [])

    return (
        <div>return something</div>
    )
};


export default EmpTable;

当我打印 employee 它只打印初始值。

但是当打印结果时,控制台显示我从 API.

获得的所有数据

加载 page/component 后,我只使用了 useEffect 运行,但它不起作用。

谁能帮我解决这个问题?

setEmployee是异步方法,所以不能在setEmployee.

后立即获取employee的更新值
setEmployee({result});
console.log(employee); // This will show the old `employee` value.

您应该通过添加 employee 依赖项在 useEffect 中获得更新的结果。

useEffect(() => {
        client
            .query({
                query: gql`
                query {
                  employees {
                    name
                  }
                }
                `
            })
            .then(result => {
              setEmployee({result});
              console.log(employee);
            });
}, [])

useEffect(() => {
  console.log(employee);
}, [employee]);

您需要使用 useEffect 钩子来实现。

有关如何在 React 挂钩上使用 setState 回调的更多信息

你的代码应该是:

import React, { useEffect, useState } from 'react';
import client from '../gqlClient';
import { gql, ApolloClient, InMemoryCache  } from '@apollo/client';


const client = new ApolloClient({
  uri: 'http://localhost:8000/graphql/',
  cache: new InMemoryCache(),
});


function EmpTable() {

  const [employee, setEmployee] = useState({});

    useEffect(() => {
        client
            .query({
                query: gql`
                query {
                  employees {
                    name
                  }
                }
                `
            })
            .then(result => {
              setEmployee({result});
              
            });
    }, [])

   useEffect(() => {
      console.log(employee);
   }, [employee]);

   return (
      <div>{JSON.stringify(employee,null,2)}</div>
   )
};


export default EmpTable;

还有另一种解决方案,您可以使用自定义挂钩在您要使用的任何组件中使用您的返回值。

import React, { useEffect, useState } from 'react';
import client from '../gqlClient';
import { gql, ApolloClient, InMemoryCache  } from '@apollo/client';


const client = new ApolloClient({
  uri: 'http://localhost:8000/graphql/',
  cache: new InMemoryCache(),
});

const useCustomApi=()=>{
    const [employee, setEmployee] = useState({});
    useEffect(() => {
        client
            .query({
                query: gql`
                query {
                  employees {
                    name
                  }
                }
                `
            })
            .then(result => {
              setEmployee({result});
              
            });
    }, [])


return employee;
}

function EmpTable() {

    const employee = useCustomApi();
    console.log(employee);

   return (
      <div>{JSON.stringify(employee,null,2)}</div>
   )
};


export default EmpTable;