gpt4 book ai didi

reactjs - React Router - 父级在导航子路由时重新渲染

转载 作者:行者123 更新时间:2023-12-05 07:22:03 26 4
gpt4 key购买 nike

如果我有根 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'

关于reactjs - React Router - 父级在导航子路由时重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56665738/

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