【发布时间】:2021-02-05 04:11:40
【问题描述】:
如果我有一个根 store 组件,并且我在其中嵌入了一个产品组件,该组件使用路由 /product/:id 呈现产品,那么根 / 每次我更改产品时呈现的行为是否正常?
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);
使用此示例代码,每次从任何/product/* 更改为另一个/product/* 时,根store 都会重新渲染。
如果只有孩子发生变化,是否有推荐的方法来防止根重新渲染?
我正在使用react-router v5。可以测试代码here
【问题讨论】:
-
已在此处提出问题 "stackoverflow.com/questions/48314909/…" 但答案不适用于上面的代码。
标签: reactjs react-router