简体   繁体   English

State 未定义,即使在 React 中初始值为 state

[英]State undefined even with initial state in React

I declared a state named product with initial values.我声明了一个名为 state 的具有初始值的product However it appears as undefined once before loading the new values.然而,它在加载新值之前显示为未定义一次。 This causes problems when I want to map its value.当我想要 map 它的值时,这会导致问题。

import React, { useEffect, useState } from 'react';
import './App.css';
import { useQuery, gql } from "@apollo/client";
import { LOAD_PRODUCT } from "./GraphQL/Queries";

import Product from './Components/Product';

function App() {

    const { error, loading, data } = useQuery(LOAD_PRODUCT)
    const [product, setProduct] = useState<Product>({
      node: {
        id: 0,
        title: "Test"
      }
    })
    
    useEffect(() => {
         setProduct(data)
     }, [data])


    if(loading) return <h1>Loading...</h1>

    console.log(product)

  return (
    <>
    <Product product={product}/>
    </>
  );
}

export default App;

在此处输入图像描述

So I'm assuming data is undefined before it's fetched from your database.所以我假设data在从您的数据库中获取之前是未定义的。 And therefore loading returns true meanwhile.因此loading同时返回true Since loading = true before data is available, your component is returning <h1>Loading...</h1> .由于loading = truedata可用之前,您的组件正在返回<h1>Loading...</h1> And therefore is not reaching your console.log(product) .因此没有到达您的console.log(product) I suspect that if you move console.log(product) to right before the if(loading) return <h1>Loading...</h1> , you'll get the result you need.我怀疑如果您将console.log(product)移动到if(loading) return <h1>Loading...</h1>之前,您将获得所需的结果。 So in the beginning it WILL print out the initial value, however it will change the initial value to undefined (using setProduct ) after that, and finally when the data is fetched it'll setProduct to the data .所以一开始它会打印出初始值,但是之后它会将初始值更改为未定义(使用setProduct ),最后当获取数据时它会将setProduct设置为data Let me know if that works out for you, I played with the code a little bit on my end.让我知道这是否适合你,我在我这边玩了一下代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM