尚方寶劍之說
2022-10-08 17:50:13
我有以下代碼:import React, { Component } from 'react';import '../styles/CountryDetails.css';import { Link } from 'react-router-dom';import { IconContext } from 'react-icons';import { GoArrowRight } from 'react-icons/go';import { FaPlane } from 'react-icons/fa';class CountryDetails extends Component { constructor(props) { super(props); this.state = { countryData: props.countryData } } render() { console.log(this.state.countryData); return ( <div> <h1 className="display-3 text-center my-5">{this.state.countryData.countryClassification}</h1> <div className="CountryDetail"> <div className="cards shadow-1 container"> <div className="row vertical-align"> <div className="col-2 text-center"> <IconContext.Provider value={{ color: '#A9A9A9', className: 'icon-hover icon-size'}}> <div> <FaPlane /> </div> </IconContext.Provider> </div> <div className="col-8"> <h4>Airfare | Car Rental | Hotel Booking Site</h4> {this.state.countryData.topAirfareCarRentalHotelBookingSite1 ? null : <span className="category-status">Under Construction...</span>} </div>這就是我得到的:現在,我的 URL 鏈接正在顯示http://localhost:8080/country/Afghanistan/。當我單擊矩形框時,我希望我的 URL 鏈接能夠更新,http://localhost:8080/country/Afghanistan/topAirfareCarRentalHotelBookingSite1并且它會顯示一個不同的組件。出于某種原因,我無法使這個 div 可點擊,并且當我點擊它時 URL 不會改變。我在使用這個代碼嗎<Link to={`/country/${this.state.countryData.countryAndTerriority}/topAirfareCarRentalHotelBookingSite1`} />錯了還是放錯了地方?
3 回答

三國紛爭
TA貢獻1804條經驗 獲得超7個贊
作為其他答案的替代方案,您可以使用功能組件并執行以下操作:
import React, { useCallback } from 'react'
import { useHistory } from 'react-router-dom'
export default ({ countryData }) => {
const history = useHistory()
const onClick = useCallback(() => {
const to = `/country/${countryData?.countryAndTerriority}/topAirfareCarRentalHotelBookingSite1`
history.push(to)
},[countryData, history])
return (
<div onClick={onClick}>
{'Your content here'}
</div>
)
}
編輯:
我認為這是您情況的最佳方法,您實際上并不需要此組件的狀態,因為您已經擁有道具。
添加回答
舉報
0/150
提交
取消