首页 > 解决方案 > React-router 未呈现动态组件-单击时没有任何反应

问题描述

我正在做一个小项目,并有一个显示有关国家/地区信息的组件列表。现在我添加了反应路由器,这样当我点击一张卡片时,它会显示有关该国家/地区的更多信息。现在,当我点击卡片时,什么也没有发生!下面是国家代码。

import React, { Component } from 'react';
import { CountryList } from './Components/Card-List/CountryList';
import { SearchBox } from './Components/Search-box/Search-Box';
import './Countries.styles.css';
import  { DetailCountryCard }  from './Components/DetailCountryCard/DetailCountryCard';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';


class Countries extends Component {
constructor() {
    super();
    this.state = {
        countries:[],
        searchField:"",
        regionField:"",
        darkMode: false
    }
    this.setDarkMode = this.setDarkMode.bind(this);
};

componentDidMount() {
    fetch("https://restcountries.eu/rest/v2/all")
    .then(response => response.json())
    .then(all =>  this.setState({ countries: all,
        regions: all}))
    .catch(error => console.log("I have errored" + error));
}
setDarkMode(e){
    this.setState((prevState) => ({ darkMode: !prevState.darkMode }));
}
render() {
    const { countries, searchField, regionField, darkMode } = this.state;
    const filterCountries = countries.filter((country) => country.name.toLowerCase().includes(searchField.toLowerCase()) &&
     country.region.toLowerCase().includes(regionField.toLowerCase()));

     return(
        <Router>
            <div className={darkMode ? "dark-mode" : "light-mode" }>
                <nav className="navbar-items">
                    <h1 className="header">Where in the World</h1>
                    <div className="moon-end">
                    <button onClick={this.setDarkMode}>
                    <i className={darkMode ? "moon fas fa-moon" : "moon far fa-moon" }></i> 
                    </button>
                    <h2>{darkMode ? "Dark Mode" : "Light Mode" }</h2>



                    </div>
                </nav>


                <div className="Input">

                    < SearchBox type="search" placeholder="Search a Country" handlechange={e=> this.setState({
                        searchField: e.target.value })}
                        />

                        < SearchBox type="regions" placeholder="Filter by Regions" handlechange={e=> this.setState({
                            regionField: e.target.value })}
                            />

                </div>
                <CountryList countries={filterCountries} />

                    {/* <Route path="/" exact component={Countries} /> */}
                   <Switch>
                    <Route path="/card-detail/:name" component={ DetailCountryCard } exact/>
                    </Switch>

            </div>
            </Router>
    );
   }
 }

export default Countries

每张卡的链接位于以下组件中:

import React from 'react';
import './CountryList.styles.css';
import {Link} from 'react-router-dom'
import { CountryCard } from '../Card/CountryCard';

export const CountryList = (props) => (
<div className='card-list'>
{props.countries.map(country => (
   <Link to={`/card-detail/${country.name}`} >
   <CountryCard key={country.alpha2Code} country={country} />
   </Link>
 ))}

</div>
);

这应该转到以下组件:

import React from 'react';
import { useEffect } from 'react';
import { useState } from 'react';


export const DetailCountryCard = ({match}) => {
useEffect(() => {
    fetchItem();
    console.log(match);
},[])

const [country, setCountry] = useState([])

const fetchItem = async ()=> {
  const fetchCountry = await    fetch(`https://restcountries.eu/rest/v2/name/${match.params.name}`);
  const countries = await fetchCountry.json();
  setCountry(countries);
  console.log(country);

 }

  return (
    <div>
        {country.map(town => (

   <div>

    <h1 key={town.alpha2Code}>{town.name}</h1>
    <p>Native Name{town.nativeName}</p>
    <p>Region: {town.region}</p>
    <p>Languages: {town.languages[0].name}</p>
  </div>

  ))}
    </div>
);
}

不知道我错过了什么。我认为我没有在组件上打错字。所以不知道为什么它不渲染?任何帮助,将不胜感激。

标签: javascriptreactjsreact-router-dom

解决方案


您只需要在 DetailCountryCard 中添加matchin useEffect 的依赖项。因为[]s similar in Class ComponentcomponentDidMount()` 并且您需要在匹配时监听它已更改。

这是最终代码DetailCountryCard

import React from "react";
import { useEffect } from "react";
import { useState } from "react";

export const DetailCountryCard = ({ match }) => {
  useEffect(() => {
    fetchItem();
    console.log(match);
  }, [match]);

  const [country, setCountry] = useState([]);

  const fetchItem = async () => {
    const fetchCountry = await fetch(
      `https://restcountries.eu/rest/v2/name/${match.params.name}`
    );
    const countries = await fetchCountry.json();
    setCountry(countries);
    console.log(country);
  };

  return (
    <div>
      {country.map(town => (
        <div>
          <h1 key={town.alpha2Code}>{town.name}</h1>
          <p>Native Name{town.nativeName}</p>
          <p>Region: {town.region}</p>
          <p>Languages: {town.languages[0].name}</p>
        </div>
      ))}
    </div>
  );
};

我在 CodeSandBox 中进行了测试,它可以工作! 关联


推荐阅读