好的,首先让我给出我正在使用的路线
<Header />
<Routes>
<Route path="/" element={<Navigate replace to="/all" />} />
<Route path="/product" element={<ProductDetail />} />
<Route path="/cart" element={<Cart />} />
<Route path="/:category" element={<ProductListing products={this.state.products} />} />
</Routes>
所以我有路径类别
<div className="right__bar">
<div className='nav_link'><Link to={"/all"}>ALL</Link></div>
<div className='nav_link'><Link to={"/clothes"}>CLOTHES</Link></div>
<div className='nav_link'><Link to={"/tech"}>TECH</Link></div>
<div className='nav_link'><Link to={"/cart"}>CART</Link></div>
</div>
当我单击“全部”链接,然后单击“衣服”时,ProductListing 组件不会重新渲染,可能是因为它们使用相同的 Prop 和相同的组件,当我从产品列表中单击“衣服”时,它们有实现差异只显示服装类产品
在下面我粘贴了我的 ProductListing 组件
import React, { Component } from 'react';
// import { useParams } from 'react-router-dom';
import { Card } from '../../components'
import "./ProductListing.scss"
export class ProductListing extends Component {
constructor(props){
super(props);
this.state ={
productsToRender:{},
loading:true,
}
}
componentDidMount(){
let {products} = this.props;
const currentUrl = window.location.href;
// I am checking if the all is present in the url i will set productsToRender
// I am facing a weired issue that is the props are not accessible to the inside if blocks
if(currentUrl.search("all")!==-1){
this.setState({
productsToRender:products[0],
loading:false,
})
}else if(currentUrl.search("clothes")!==-1){
this.setState({
productsToRender:products[1],
loading:false,
})
}else if(currentUrl.search("tech")!==-1){
this.setState({
productsToRender:products[2],
loading:false,
})
}
}
render() {
console.log("I am executed")
if(this.state.loading === true){
return <h1>LOADING....</h1>
}else{
return (
<div>
<h2>{this.state.productsToRender.name}</h2>
<div className="product__listing">
{this.state.productsToRender.products.map((item,index)=>(
<Card product={item}/>
))}
</div>
</div>
)
}
}
}
export default ProductListing
最佳答案
您可以使用 useParams
钩子(Hook)来代替 window.location.href
,它会返回您当前的 :category
关于javascript - 当我使用 React Router ROM 时,组件不会重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72303028/