[英]React Component Infinite Re-render
I have a React component structure: 我有一个React组件结构:
CookiesProvider
| App
| BrowserRouter
| AppContext.Provider
| Layout
| Switch
| Route path="all-products" component={Gallery}
When I refactor the code and pull the entire Switch/Routes structure into a stateless component or when I put the BrowserRouter component outside the CookieProvider component, the Gallery component gets infinitely re-rendered. 当我重构代码并将整个Switch / Routes结构拉入无状态组件时,或者将BrowserRouter组件放在CookieProvider组件之外时,Gallery组件将无限地重新呈现。 But if I leave my structure in place, everything works fine.
但是,如果我将结构保留在原位,那么一切都会很好。
I have logged the mounting and un-mounting of the Gallery component as well as the network calls. 我已经记录了Gallery组件的安装和卸载以及网络调用。
Why could this be happing? 为什么会这样?
Current code structure: 当前代码结构:
// index.js
ReactDOM.render((
<CookiesProvider>
<Home />
</CookiesProvider>
), document.getElementById('root'));
// render() of Home component
const galleryRefresh = this.state.galleryRefresh
return (
<BrowserRouter>
<AppContext.Provider value={this.state.context}>
<Layout>
<Switch>
<Route path="/all-products" component={()=> {
return <Gallery refresh={galleryRefresh} otherFilters={["type:clothes"]}/>
}}/>
</Switch>
</Layout>
</AppContext.Provider>
</BrowserRouter>
)
When I refactor the Routes logic: 当我重构Routes逻辑时:
// render() of Home Component
const galleryRefresh = this.state.galleryRefresh
return (
<BrowserRouter>
<AppContext.Provider value={this.state.context}>
<Layout>
<Route galleryRefresh={galleryRefresh}/>
</Layout>
</AppContext.Provider>
</BrowserRouter>
)
// Routes stateless component
const Routes = ({galleryRefresh}) => (
<Switch>
<Route path="/all-watches" component={()=> {
return <Gallery refresh={galleryRefresh} otherFilters={["type:Watch OR watch"]}/>
}}/>
</Switch>
)
In the Route component, I am supposed to be using the render
prop instead of the component
prop. 在Route组件中,我应该使用
render
prop而不是component
prop。
<Switch>
<Route path="/all-products" render={()=> {
return <Gallery refresh={galleryRefresh} otherFilters={["type:clothes"]}/>
}}/>
</Switch>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.