如何在获取信息之前使用地图功能 React js

How to use map function before fetch info React js

我正在用这种结构做一个主页

const Login: React.FC = () => {

  [ ... ]

  return (
    <IonPage>


      <IonContent>

          <IonSlides pager={false} options={slideOpts}>
            {
              responseProducts.content.products.map(function(item,i) {
                return <IonSlide key={i} >
                        <IonCard onClick={Product}>
                          <IonImg src={item.urlImg}></IonImg>
                          <IonCardHeader>
                            <IonCardSubtitle>{item.ref}</IonCardSubtitle>
                            <IonCardTitle>{item.title}</IonCardTitle>
                          </IonCardHeader>
                        </IonCard>
                      </IonSlide>
              })
            }
          </IonSlides>

      </IonContent>
    </IonPage>
  );
};

当我获取服务器 api 时,变量 responseProducts.content.products 是一个产品数组。

我正在尝试获取 api 以在应用程序启动之前初始化变量:

const Login: React.FC = () => {
  /* this is the initialization of my variable with products*/
  let responseProducts : getProductsReponse;
  /* function to fetch the api*/
  useIonViewDidEnter(async () => {
    await fetchProducts();
  });


  const fetchProducts = async() =>{
    await ProductService.getProducts()
      .then((products ) =>{
         responseProducts = products.data;
      })
  }

  return (
    <IonPage>

      <IonContent>

          <IonSlides pager={false} options={slideOpts}>
            {
              responseProducts.content.products.map(function(item,i) {
                return <IonSlide key={i} >
                        <IonCard onClick={Product}>
                          <IonImg src={item.urlImg}></IonImg>
                          <IonCardHeader>
                            <IonCardSubtitle>{item.ref}</IonCardSubtitle>
                            <IonCardTitle>{item.title}</IonCardTitle>
                          </IonCardHeader>
                        </IonCard>
                      </IonSlide>
              })
            }
          </IonSlides>

      </IonContent>
    </IonPage>
  );
};

但是我在使用产品时遇到此错误:

Variable 'responseProducts' is used before being assigned

[编辑]:要在等待数据时显示不同的内容,您可以这样做:

if (!responseProducts) return <Loader />;
  else
    return (
      <IonPage>
        ...
      </IonPage>
    );

但是这里你需要触发组件的渲染。要么将您的产品置于某种状态并使用 setState,要么在您的父级中处理抓取并将您的产品作为 propr 传递(仍然需要一个状态)。


您的 responseProducts 需要一个默认值。您可以使用 useEffect 挂钩和 useState 挂钩来实现此目的:

const Login: React.FC = () => {
  const [products, setProducts] = useState({});
  const [didMount, setDidMount] = useState(false);

  useEffect(() => {
    if(!didMount){
      // I don't know where this comes from so i'll use it like this, adapt if needed
      useIonViewDidEnter(async () => {
        await fetchProducts();
      });
    } else {
      !didMount && setDidMount(true);
    }
  });

  /* this is the initialization of my variable with products*/
  let responseProducts: getProductsReponse;
  /* function to fetch the api*/


  const fetchProducts = async () => {
    await ProductService.getProducts().then((products) => {
      // responseProducts = products.data;
      const data: getProductsReponse = products.data;
      setProducts(data);
    });
  };

  // You could even put a different return (a loader for exemple) while your data arent available
  return (
    <IonPage>
      <IonContent>
        <IonSlides pager={false} options={slideOpts}>
          {/* this is now strange, you can adapt what you put in your state */}
          {products.content.products.map((item, i) => {
            return (
              <IonSlide key={i}>
                <IonCard onClick={Product}>
                  <IonImg src={item.urlImg}></IonImg>
                  <IonCardHeader>
                    <IonCardSubtitle>{item.ref}</IonCardSubtitle>
                    <IonCardTitle>{item.title}</IonCardTitle>
                  </IonCardHeader>
                </IonCard>
              </IonSlide>
            );
          })}
        </IonSlides>
      </IonContent>
    </IonPage>
  );
};