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

问题描述 投票:0回答:3

所以我很难解决这个问题。通常,我只会做一个“ ComponentDidMount”,但是由于我试图避免使用类,而只使用React钩子,所以我陷入了问题。

我的组件在从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;
    }
  }
javascript reactjs redux react-hooks lifecycle
3个回答
1
投票
if(!userShop){
   return <h1>loading<h1>;
 }
 return (
     <div>
      {userShop.map(shop=>(<div>{shop}</div>))}
   </div>
 );

0
投票

如果使用state.shopundefined设为short-circuit evaluation,则返回一个空数组:

const userShop = useSelector(state => state.shop || []);

0
投票
return (
     <div>
      {userShop && userShop.map(shop=>(<div>{shop}</div>))}
   </div>
 );
© www.soinside.com 2019 - 2024. All rights reserved.