Ine*_*esM 0 reactjs react-router
我正在使用 react-router (v.4.3.1) 来渲染我的应用程序的主要部分,我在左侧有一个带有菜单的抽屉。当在应用程序标题中切换按钮时,我正在更改折叠变量的状态,以便组件重新渲染 css。我的问题是这个变量需要存储在渲染所有我Route
的组件上,当组件更新时Route
正在卸载和安装它的组件。
我已经尝试向key
我提供一个,Route
但它不起作用。
我的代码看起来像这样,这个组件的父级是正在更新的重新渲染我的Main
组件的父级:
class Main extends Component {
constructor(props) {
super(props);
this.observer = ReactObserver();
}
getLayoutStyle = () => {
const { isMobile, collapsed } = this.props;
if (!isMobile) {
return {
paddingLeft: collapsed ? '80px' : '256px',
};
}
return null;
};
render() {
const RouteWithProps = (({index, path, exact, strict, component: Component, location, ...rest}) =>
<Route path={path}
exact={exact}
strict={strict}
location={location}
render={(props) => <Component key={"route-" + index} observer={this.observer} {...props} {...rest} />}/>
);
return (
<Fragment>
<TopHeader observer={this.observer} {...this.props}/>
<Content className='content' style={{...this.getLayoutStyle()}}>
<main style={{margin: '-16px -16px 0px'}}>
<Switch>
{Object.values(ROUTES).map((route, index) => (
<RouteWithProps {...route} index={index}/>
))}
</Switch>
</main>
</Content>
</Fragment>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望 Route 只是更新而不是卸载组件。这可能吗?
由于RouteWithProps
在渲染方法内部定义,您遇到此问题。这会导致 React 在每次调用 render 方法时卸载旧的并安装一个新的。实际上在 render 方法中动态创建组件是一个性能瓶颈,被认为是一种不好的做法。
只是移动的定义RouteWithProps
出来的Main
组成部分。
大致的代码结构如下:
// your impors
const RouteWithProps = ({observer, path, exact, strict, component: Component, location, ...rest}) =>
<Route path={path}
exact={exact}
strict={strict}
location={location}
render={(props) => <Component observer={observer} {...props} {...rest} />}/>;
class Main extends Component {
...
render(){
...
{Object.values(ROUTES).map((route, index) => (
<RouteWithProps key={"route-" + index} {...route} observer={this.observer}/>
))}
^^^ keys should be on this level
...
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2128 次 |
最近记录: |