猿问

ReactJS,功能组件。所以我想根据点击 <Link> 来设置状态

例如,我有一个菌株列表,每个菌株都位于从 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;


ibeautiful
浏览 115回答 1
1回答

慕尼黑8549860

你想要的是一种访问路由参数的方法(在你的情况下是应变),像这样在渲染回调中将路由器道具传递给你的组件<Route&nbsp;exact&nbsp;path='/strains/:strain'&nbsp;render&nbsp;=&nbsp;{(props)&nbsp;=>&nbsp;<Strain&nbsp;{...props}&nbsp;strains={strains}&nbsp;addToSavedList={addToSavedList}&nbsp;/>}&nbsp;/>现在在您的应变组件中,您可以像这样访问参数const&nbsp;Strain&nbsp;=&nbsp;({match})&nbsp;=>&nbsp;{&nbsp; &nbsp;&nbsp;console.log(match.params) &nbsp;&nbsp;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答