如何 运行 具有默认 "id" 的函数开始使用 useEffect 挂钩进行反应?

How to run a function with default "id" on start using useEffect hook in react?

我正在制作一个简单的博客 post 网站,用户可以在其中 post 一个条目。

objective 是: 让主页在列表中显示所有博客 post,并在主页首次加载时在其旁边显示任何一个博客的详细信息 post。当用户单击列表中的任何项目时,其详细信息将替换默认的博客详细信息。 Indeed 基本上是如何显示职位的 posts.

方法: 我进行了 2 个 Axios 调用,一个是获取所有数据,另一个是通过 id 获取数据。 来自 getAllData 的数据显示在 HomePage 上的列表中数据作为 props 传递给 HomePageListItems,它们被包装在 /${idx}}/>

我使用 useParams 获取 ID 并在 DataById 中调用 getDataId。

所以,HomePage 必须有子组件 HomePageListItems 和 DataById 问题是:

  1. 首次加载主页时,函数 getDataById 不起作用。它仅在路由为“localhost/:id”时有效,即“localhost:3000/ae86140b-7ae6-457-826c-5bd324b8cb3”

  2. 因为我希望在第一次加载时已经显示一个博客:我如何使用带有预设 ID 的 getDatabyId 函数 运行,当用户单击列表项时,该 ID 会发生变化?

密码是:

import React, { useState, useEffect, usePrevious } from "react";
import { Link, useParams } from "react-router-dom";
import Axios from "axios";
import HomePageListItems from "./homePageListItems";
import DataById from "./dataById";

export default function HomePage(props){
  <DataById/>
    const [getAllData, setGetAllData] = useState()
    const getData =async () => {
      await  Axios.get("http://localhost:5000/get").then((response)=>{
        setGetAllData(response.data)
        })
        .catch((error)=>{console.log(error)})
    }
    useEffect(()=>{
        getData();
      },[])
    return(
        <section>
          <Link to = "/postJournal">Post Journal Entry</Link>
            {getAllData&&getAllData.map((item)=>{
                return(
                    <HomePageListItems
                    key={item.id}
                    idx={item.id}
                    name={item.name}
                    title={item.title}
                    journalEntry={item.journalEntry}
                    date={item.date}
                    file={item.file}
                    />
                )
            })
            
        }
         {usePrevious}
        <DataById/>
        </section>
        
    )
}

--

    import React, { useState, useEffect, usePrevious } from "react";
    import { useParams } from "react-router-dom";
    import Axios from "axios";
    
    export default function DataById(props){
      console.log("DataProps",props)
      const [axiosGetData, setAxiosGetData] = useState([])
      const {id} = useParams()
      const getDataById =async () => {
            await  Axios.get(`http://localhost:5000/${id}`).then((response)=>{
              setAxiosGetData(response.data[0])
                  console.log("Data",response.data[0])
              })
              .catch((error)=>{console.log(error)})
          }
          useEffect(()=>{
            getDataById("35b48be0-0ab8-4409-a5eb-a0c4dbd0a4b3");
          },[id])
    
        return(
          <>
          <p> DataByID</p>
            name:{axiosGetData.name}
            Date:{axiosGetData.date}
            Journal:{axiosGetData.journalEntry}
            {usePrevious}
          </>
        
        )
    
    }  

--

    import React, { useState, useEffect, usePrevious} from "react";
    import { Link} from "react-router-dom";
    
    export default function HomePageListItems(props){
        let {name,title,journalEntry,date,file,idx}=props
        return(
            <main className= "homepage">
               <Link to={`/${idx}`} >
                <section className="homepage__listContainer">
                    <ul className = "homepage__list">
                        <li className="homepage__listItemWrapper">
                            <div className ="homepage__listItem">
                                <div className = "homepage__listItemImgWrapper">
                                    <img className = "homepage__listItemImg" alt="" src={file}/>
                                </div>
                                <h3 className= "homepage__listItemTitle">Title:{title}</h3>
                                <p className = "homepage__listItemAuthor">Name:{name}</p>
                                <p className = "homepage__listItemDescription">Description:{journalEntry}</p>
                                <p className = "homepage__listItemDate">Posted Date:{date}</p>
                                <p>Key:{idx}</p>
                            </div>
                        </li>
                    </ul>
                </section>
                 </Link>
                {usePrevious}  
            </main>
          
        )
    }

--
import React from "react";
import "./style/App.css";
import ReactDOM from 'react-dom';
import { BrowserRouter, Switch, Router, Route } from "react-router-dom";
import HomePage from "./components/homePage"
import PostJournalEntry from "./components/postJournalEntry"
import DataByIDfrom "./components/dataById"


function App() {
  return (
    <div className="app">
      <BrowserRouter>
      <Switch>
      <Route path="/:id" exact component = {HomePage}/>
      <Route path="/:id" exact component = {DataByID}/>
      <Route path="/postJournal" exact component = {PostJournalEntry}></Route>
      <Route path="/" exact component = {HomePage}/>
      </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

提前谢谢大家!提供任何帮助。

因为 getDataById 不接受任何参数,它总是使用 URL id (useParams) 进行 axios get 调用,在 useEffect 中传递一个 id 不会做任何事情。您需要向函数添加一个参数,然后添加一些逻辑,以便它知道是使用传入值还是使用 URL id 值。你可以尝试这样的事情:

      const getDataById = async (startupId = null) => {
            await  Axios.get(`http://localhost:5000/${startupId ? startupId : id}`).then((response)=>{
              setAxiosGetData(response.data[0])
                  console.log("Data",response.data[0])
              })
              .catch((error)=>{console.log(error)})
          }

这样,如果您向 getDataById 传递一个参数,它将使用该值进行 axios 调用,否则它将尝试使用 useParams

中的 id 值