}/> -6ren">
gpt4 book ai didi

javascript - 路径和向其传递 Prop 的问题(带有 map 的组件)

转载 作者:行者123 更新时间:2023-11-28 03:06:29 24 4
gpt4 key购买 nike

我有一个相当复杂的问题,我知道我可能完全错误地完成了它,但我不知道如何使用 this.props.match.params 和路线 path = "/:car-category.

<Route exact path={"/car-VAN/"} component={() => <CarCategory category={"VAN"} link={"/car-VAN/"}/>}/>
<Route exact path={"/car-SUV/"} component={() => <CarCategory category={"SUV"} link={"/car-SUV/"}/>}/>

import React, {Component} from 'react';
import '../sass/main.scss';
import {Helmet} from "react-helmet";
import {
Link
} from 'react-router-dom';


const car1 = {
carName: 'car-name-1',
cat: 'VAN',
vin: '31321414124214',
};

const car2 = {
carName: 'car-name-1',
cat: 'SUV',
vin: '31321414124321',
};

const carAll = [car1, car2, car3];

class CarCategory extends Component{

render() {

const {category, link} = this.props;
let sortCar = carAll.filter( el => el.cat === category );

return(
<> <section className='cars-section'>
<div className='container'>
<Helmet>
<title>{category}</title>
</Helmet>
<h1 className='head-text-category-mobile'>{category}</h1>
<div className='cars-gallery-container'>
{
sortCar.map(el => {
{
return(<React.Fragment key={el.vin}>
<div className='one-car-container'>
<Link to={link + el.carName}>
<div className='car-div'>
<div className='car-name'>{el.carName}</div>
</div>
</Link>
</div>
</React.Fragment>
)
}
})
}
</div>
</div>
</section>
</>
)
}
}

export default CarCategory

我的英语不好,我无法更好地解释它,我希望有人能理解并帮助我

最佳答案

您可以通过将路线设置为使用参数使其动态化:

<Route exact path={"/car-:category"} component={CarCategory} />

汽车类别:

class CarCategory extends React.Component {
render() {

const { category } = this.props.match.params;
const link = `/car-${category}/`;

let sortCar = carAll.filter(el => el.cat === category);

return (
...
...
);
);

这可行,但我会避免使用像 /car-:category 这样的路线。相反,像 /car/:category 那样将其分解。

关于javascript - 路径和向其传递 Prop 的问题(带有 map 的组件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60564763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com