【问题标题】:How to use route params in same component in React (react-router-dom v6)如何在 React 的同一组件中使用路由参数(react-router-dom v6)
【发布时间】:2022-11-29 09:01:35
【问题描述】:

我如何通过ID/profile/:id到函数generateProfile(findProfile(id))

下面是我的代码

import { Routes, Route } from 'react-router-dom';
import Profile from './Profile';
import '../assets/styles/App.css';
import seedProfiles from '../seedProfiles';
import generateProfile from '../helpers/profileHelper';

function App() {  
  const findProfile = id => seedProfiles.find(profile => profile.id === id);

  return (
    <Routes>
      <Route exact="true" path="/" element={<h1>PROFILES</h1>} />
      <Route 
         exact="true" 
         path="/profile/:id" 
         element={<Profile profile={generateProfile(findProfile(???))} />} 
      />
    </Routes>
  );
}

export default App;

谢谢

【问题讨论】:

  • 尝试使用 let { id } = useParams();在 Profile 组件中
  • 我试过了,但在同一个 App 组件中不起作用。
  • 是否可以通过 Profile 函数 const generateProfile = id => generateProfile(findProfile(id)) 和 useMemo 或 useEffect 来设置配置文件,因为 useParams 需要上下文
  • 使用 window.location 或 window.location.href 通常不是一个好主意,因为 React 不会与这些更改同步
  • 这就是 useParams 钩子的用途。但是为什么你需要这样做呢?为什么不将此逻辑移至 Profile 而不是将其作为 props 传递并使用该组件中的钩子来获取动态参数?

标签: reactjs react-router react-router-dom


【解决方案1】:

路由路径参数只能通过 useParams 挂钩访问。如果需要访问路由路径参数事先的要呈现路由组件,那么您需要创建一个包装组件,它可以“嗅探”参数并应用任何逻辑。

例子:

const ProfileWrapper = ({ getProfile }) => {
  const { id } = useParams();
  return <Profile profile={getProfile(id)} />
};

function App() {  
  const getProfile = id => generateProfile(
    seedProfiles.find(profile => profile.id === id)
  );

  return (
    <Routes>
      <Route path="/" element={<h1>PROFILES</h1>} />
      <Route 
         path="/profile/:id" 
         element={<ProfileWrapper profile={getProfile} />} 
      />
    </Routes>
  );
}

但是,更常见的做法是将此逻辑移动到正在呈现的组件中,因为实际上没有任何父依赖项。

例子:

import { Routes, Route } from 'react-router-dom';
import Profile from './Profile';
import '../assets/styles/App.css';
import seedProfiles from '../seedProfiles';
import generateProfile from '../helpers/profileHelper';

const Profile = () => { 
  const { id } = useParams();

  const profile = generateProfile(seedProfiles.find(profile => profile.id === id));

  return ...;
}
import { Routes, Route } from 'react-router-dom';
import Profile from './Profile';
import '../assets/styles/App.css';

function App() {  
  return (
    <Routes>
      <Route path="/" element={<h1>PROFILES</h1>} />
      <Route path="/profile/:id" element={<Profile />} />
    </Routes>
  );
}

【讨论】:

    猜你喜欢
    • 2022-07-09
    • 2021-11-03
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多