如果我有一个根
使用此示例代码,每次从任何
是否有建议的方法可以防止根节点在只更改子节点时重新呈现?
我正在使用
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
。 您可以在此处测试代码。