【发布时间】: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