【问题标题】:How do I render Data with Relay ,GraphQL and React如何使用 Relay、GraphQL 和 React 渲染数据
【发布时间】:2021-04-28 11:47:51
【问题描述】:

当我尝试使用来自 Django 后端的 GraphQL 将数据提取到 React 前端时出现此错误 错误

index.js:1 Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information.
    at EmployerInfo (http://localhost:3000/static/js/main.chunk.js:231:75)
    at div
    at ApolloProvider (http://localhost:3000/static/js/0.chunk.js:6401:19)
    at App

这是在 React 前端获取的反应代码

const QUERY_EMPLOYERS = gql`
{
    allEmployers{
      edges{
        node{
          id
          employerName
          email
          phone
          
        }
      }
    }
  }
`;
export function EmployerInfo() {
  const { data, loading } = useQuery(QUERY_EMPLOYERS, {pollInterval: 500});
  
  
  if (loading) return <p>Loading...</p>;
   
  return data?.allEmployers.edges.map(({ id, employerName, email, phone }) => (
    <div key={ id }>
      <p>
        Employer - { employerName } { email }  { phone }
      </p>
    </div>
  ));
}

【问题讨论】:

    标签: reactjs django graphql


    【解决方案1】:

    我认为你的一些ids 是重复的,试试这个:

    export function EmployerInfo() {
      const { data, loading } = useQuery(QUERY_EMPLOYERS, { pollInterval: 500 });
    
      if (loading) return <p>Loading...</p>;
    
      return data?.allEmployers.edges.map(
        ({ id, employerName, email, phone }, index) => (
          <div key={`${id}-${index}`}>
            <p>
              Employer - {employerName} {email} {phone}
            </p>
          </div>
        )
      );
    }
    

    【讨论】:

    • 错误消失,但没有在前端呈现数据。
    【解决方案2】:

    我用下面的代码解决了这个问题

    export function EmployerInfo() {
      const { data, loading } = useQuery(QUERY_EMPLOYERS, { pollInterval: 500 });
    
      if (loading) return <p>Loading...</p>;
    
      const employers = data.allEmployers.edges;
    
      return(
          <div>
            { employers.map( employer => {
              return <p key={employer.node.id}> Employer -  {employer.node.employerName} {employer.node.email} {employer.node.phone} </p>
            })}
          </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-12
      • 2018-02-12
      • 2016-04-11
      • 2018-05-15
      • 2018-03-20
      • 2017-03-17
      • 1970-01-01
      • 2016-02-10
      • 2017-09-04
      相关资源
      最近更新 更多