如何使用 useEffect 挂钩从产品中获取类别?

catId下午好,我不明白为什么我无法从产品中获取类别。也就是说,首先我useState分别为产品和类别创建一个。然后,使用axios和useEffect,我通过 slug 通过我的 API 获取产品。(产品一切都好,一切都很酷)接下来我也想获取类别,我需要传递参数catId,并且从之前收到的产品中不起作用。


下面是代码:


import logo from './logo.svg'

import './App.css'


import React, {useState, useEffect} from 'react'

import axios from 'axios'


const App = () => {


  const [product, setProduct] = useState({})

  const [category, setCategory] = useState({})


  useEffect(() => {

    const fetchProduct = async () => {

      const {data} = await axios.get('/api/products/random-lucky-box')


      setProduct(data)

    }


    fetchProduct()

  }, [])


  useEffect(() => {

    const fetchCategory = async () => {

      const {data} = await axios.get(`/api/categories/${product.catId}`)


      setCategory(data)

    }


    fetchCategory()

  }, [])


  return (

    <div className="App">

      <header className="App-header">

        <img src={logo} className="App-logo" alt="logo" />

        <p>

          Название: {product.name} <br />

          Цена: {product.price}

        </p>


      </header>

    </div>

  )

}


export default App

PS:API 单独测试了一切正常,例如,如果您传递静态 id 参数。我将非常感谢您的帮助!


慕容3067478
浏览 195回答 1
1回答

湖上湖

useEffect hook 就像一个生命周期,它将像 componentDidMount 一样启动,如果您希望从产品中获取类别,您需要在方法中重构您的获取类别调用,而不是 useEffect。所以当你获取产品后,你可以调用你的方法来获取类别。它将是这样的:useEffect(() => {&nbsp; &nbsp; const fetchProduct = async () => {&nbsp; &nbsp; &nbsp; const {data} = await axios.get('/api/products/random-lucky-box')&nbsp; &nbsp; &nbsp; setProduct(data)&nbsp; &nbsp; &nbsp; fetchCategory(data.categoryId)&nbsp; &nbsp; }&nbsp; }, [])&nbsp; const fetchCategory = async (catId) =>&nbsp; {&nbsp; &nbsp; &nbsp;const {data} = await axios.get(`/api/categories/${catId}`)&nbsp; &nbsp; // set your state or whatever&nbsp; &nbsp; }我没有太多时间详细说明代码,您可能需要重构,但想法就是这样。您应该在获取产品数据时调用您的方法
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript