例如,我有一个菌株列表,每个菌株都位于从 react-router-dom 导入的组件中。我希望此链接将我带到 Route path='/strains/{strain}'。在这个页面上,我只想渲染被点击的菌株的名称,但是当点击一个链接时,所有菌株的名称都会被渲染。这是我显示所有路线的代码。import React, {useEffect, useState} from 'react';import { Route, Link } from 'react-router-dom';import axios from 'axios';import UserCreation from './components/UserCreation';import Login from "./components/Login";import StrainCard from './components/StrainCard';import { Container } from "reactstrap";import NavBarComponent from "./components/NavBarComponent";import SavedStrain from './components/SavedStrain';import Strain from './components/Strain';import StrainDetails from './components/StrainDetails';function App() { const [strains, setStrains] = useState([]); const [savedList, setSavedList] = useState([]); const [strain, setStrain] = useState([]); useEffect(() => { const getStrains = () => { axios .get('http://strainapi.evanbusse.com/CEIl7eN/strains/search/all') .then(response => { console.log(response); setStrains(response.data); }) .catch(error => { console.error('Server Error', error.response); }); } getStrains(); }, []);console.log(strains) useEffect(() => { setStrain(Object.keys(strains).slice(0, 20)) }, [strains]) console.log(strain) const addToSavedList = strain => { setSavedList([...savedList, strain]); }; return ( <Container className="App"> <NavBarComponent /> <Route exact path='/'> <Link to='/login'>Log in</Link> </Route> <Route exact path='/login'> <Login /> </Route> <Route exact path='/signup'> <UserCreation /> </Route> );}export default App;
1 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
你想要的是一种访问路由参数的方法(在你的情况下是应变),像这样在渲染回调中将路由器道具传递给你的组件
<Route exact path='/strains/:strain' render = {(props) => <Strain {...props} strains={strains} addToSavedList={addToSavedList} />} />
现在在您的应变组件中,您可以像这样访问参数
const Strain = ({match}) => { console.log(match.params) }
添加回答
举报
0/150
提交
取消