React 在我的组件实际拥有数据之前渲染它

React renders my Component before it actually has Data

所以我很难解决这个问题......通常我只会做一个 "ComponentDidMount" 但是因为我试图避免使用 类 并且只使用反应钩子我被卡住了有问题。

我的组件在从 API 获取任何数据之前渲染,所以我的 .map 函数将无法工作,因为它没有收到任何数据。

Shop.js

import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { listShops } from "../../Redux/actions/shopActions";

const Shop = () => {
  const userShop = useSelector(state => state.shop);
  const auth = useSelector(state => state.auth);
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(listShops(auth));
  }, []);

console.log("Look at my userShop",userShop.shop)
  return (
      <div>
       {userShop.map(shop=>(<div>{shop}</div>))}
              {console.log("How often do I Render?")}
    </div>
  );
};

export default Shop;

ShopAction.js

import {GET_SHOPS} from "./types";

export const listShops = userData => async dispatch =>{
    const userId = userData.user.id;
    await axios.get(`/api/shops/shops/user/${userId}`)
    .then(
        res => {
        const user = res.data;
        dispatch({
            type: GET_SHOPS,
            payload: user.shops
        })})
}

shopReducer.js


const initialState = {}

export default function(state = initialState, action) {
    switch (action.type) {
      case GET_SHOPS:
        return {
            ...state,
            shop:action.payload
        }
      default:
        return state;
    }
  }
if(!userShop){
   return <h1>loading<h1>;
 }
 return (
     <div>
      {userShop.map(shop=>(<div>{shop}</div>))}
   </div>
 );

Return 如果 state.shopundefined 使用 short-circuit evaluation:

一个空数组
const userShop = useSelector(state => state.shop || []);
return (
     <div>
      {userShop && userShop.map(shop=>(<div>{shop}</div>))}
   </div>
 );