您好,我正在使用 laravel 后端 REST API 和 React 作為前端。我的問題是每條路線上都有很多對用戶 api 的調用。如果我去/category我收到了一個用戶 API 請求,因為我需要有用戶信息,比如如果是管理員;用戶名;...,這是正常的,因為我在 App.js 上調用了這個 api 我試圖在 上做一個條件語句來知道componentDidMount我是否已經擁有我狀態(tài)下的用戶數(shù)據,但是 React 返回給我infinite loop一個this.setState({user: data})所以我的問題是我可以調用一次 api 嗎?或者我是否需要使用 Redux 來存儲一次用戶數(shù)據并使用這些數(shù)據?我的 App.js:import React from 'react';import axios from 'axios';import {BrowserRouter as Router, Switch, Route, Redirect} from 'react-router-dom';import Login from "./pages/Login";import Home from "./pages/Home";import Profile from "./pages/Profile";import Register from "./pages/Register";import Header from "./components/Header";import Administration from "./pages/Administration";import './assets/main.css'import './App.css'import PrivateRoute from "./components/PrivateRoute";import Category from "./pages/Category";import Product from "./pages/Product";import Order from "./pages/Order";import User from "./pages/User";import Support from "./pages/Support";export default class App extends React.Component { constructor(props) { super(props); this.state = { redirectToHome: false, isLog: false, isAdmin: false, user: null, } } componentDidMount(){ if (localStorage.getItem('token')){ axios.post('auth/me') .then((res) => { this.setUser(res.data) }) .catch((err) => { localStorage.removeItem('token') }) } } setUser = (user) => { this.setState({user: user}) } render() { if (this.state.redirectToHome){ return <Redirect to={'/'} from={'/logout'} /> } return ( <Router> <div> <Header user={this.state.user} setUser={this.setUser} /> </div>
在每個組件上調用的用戶 api
慕尼黑5688855
2023-04-01 16:35:10