如果我有根 store
组件并在其中嵌入了一个产品组件,该组件使用路由 /product/:id
呈现产品, root /
是正常行为吗, 每次我更换产品时呈现?
import React, {Component} from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Link } from "react-router-dom";
const Products = [
{ "id" : "First", info : "Great product"},
{ "id" : "Second", info : "Another Great product"},
{ "id" : "Third", info : "Some other product"},
{ "id" : "Fourth", info : "Worst product"},
]
class ProductDetail extends Component {
render(){
console.log("rendering ProductDetail");
const {match} = this.props;
const product = Products.find(({id}) => id === match.params.productId);
return <div>
<h3>{product.id}</h3>
<span>{product.info}</span>
</div>
}
}
class Product extends Component {
render(){
console.log("rendering Product");
const {match} = this.props;
return <div>
<h2>This shows the products</h2>
<ul>
{Products.map(p=><li><Link to={`${match.url}/${p.id}`}>{p.id}</Link></li>)}
</ul>
<Route path={`${match.path}/:productId`} component={ProductDetail}/>
</div>
}
}
class Store extends Component {
render(){
console.log("rendering Store");
const {match} = this.props;
return <div>
<h1>This is the Store</h1>
<Link to={`${match.url}product`}>See products</Link>
<Route path={`${match.path}product`} component={Product}/>
</div>
}
}
function App() {
console.log("rendering App");
return (
<div className="App">
<BrowserRouter>
<Route path="/" component={Store}/>
</BrowserRouter>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
使用此示例代码,根 store
每次从任何 /product/*
更改时都会重新渲染到另一个/product/*
.
如果只有子项发生变化,是否有推荐的方法来防止根重新渲染?
我正在使用 react-router v5
.可以测试代码here
最佳答案
<BrowserRouter>
<Route exact path="/" component={Store}/>
</BrowserRouter>
// I think its solve your issue add 'exact'
https://stackoverflow.com/questions/56665738/
相关文章:
javascript - 如何将 blob 转换为 xlsx 或 csv?
react-native - ScrollView : content image is cropp
apache-spark - 如何将处理程序附加到 sparkUI
amazon-web-services - 是否可以向 InputPath 添加新的键/值?
c# - 标签助手 asp-route- 不工作 - Razor Pages(.Net Core 3
google-cloud-platform - 使用 Terraformer\Terraform 克