Javascript 如何使用react router创建单页应用程序
我是React.js的新手,但我正在使用它构建一个单页应用程序。 对于路由,我使用react路由器 我想要组织我的页面的方式如下:我想要有一个静态的页眉和页脚(只加载一次),然后页面的内容将根据路由而改变。这里没什么特别的,这基本上是我对水疗的理解 这是main.js,用于引导我的应用程序使用以下路径:Javascript 如何使用react router创建单页应用程序,javascript,reactjs,react-router,react-router-redux,Javascript,Reactjs,React Router,React Router Redux,我是React.js的新手,但我正在使用它构建一个单页应用程序。 对于路由,我使用react路由器 我想要组织我的页面的方式如下:我想要有一个静态的页眉和页脚(只加载一次),然后页面的内容将根据路由而改变。这里没什么特别的,这基本上是我对水疗的理解 这是main.js,用于引导我的应用程序使用以下路径: const store = configureStore(); ReactDOM.render( <Provider store={store}> <Router hi
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="shop-filters-left-3cols" component={ShopFiltersLeft3Cols}/>
<Route path="about" component={About}/>
<Route path="login" component={Login}/>
</Route>
</Router>
</Provider>,
document.getElementById('main')
);
const store=configureStore();
ReactDOM.render(
,
document.getElementById('main')
);
这是组件应用程序,基本上包含了单页的结构:
export class App extends React.Component {
constructor(){
super();
this.render = this.render.bind(this);
}
render() {
console.log('Rendering App');
return (<div>
<LoginModal />
<Header/>
<div className="page-content">
{this.props.children}
</div>
<Footer/>
</div>);
}
}
导出类应用程序扩展React.Component{
构造函数(){
超级();
this.render=this.render.bind(this);
}
render(){
console.log('Rendering App');
返回(
{this.props.children}
);
}
}
因此,当我访问应用程序时,组件“app”被加载,然后组件“Home”被注入到主内容中,因为它被声明为IndexRoute
在这里之前一切都很好,问题是每次我从一个路由切换到另一个路由时,组件“App”都会被渲染(我知道这一点,因为我在控制台中看到了“Rendering App”日志)。这就是我不理解的,据我所知,在路由之间切换不应该触发“应用程序”组件的呈现,而只是动态注入的组件的呈现
我不希望每次切换路由时都呈现页眉和页脚,这正是使用单页应用程序的好处。
也许我不太了解react路由器的工作原理,有人能帮我吗?或者如果我做错了什么,请告诉我什么是实现我需要的正确方法
如果您需要查看任何其他代码,请毫不犹豫地询问。谢谢重新呈现
应用程序
组件,因为您说它是视图的根:
<Route path="/" component={App}>
这不是问题。React设计用于重新呈现组件
,您应该记住这一点
为什么不是问题?
与大多数模板系统不同,React调用的呈现不一定涉及DOM更改。当React“重新呈现”一个组件时,它计算将DOM从当前状态转换为所需状态的最小操作集。这可能是一个空集
换句话说,对于生成相同HTML的组件
,实际上什么也不做。您的页眉和页脚可能属于这一类
这使得它非常快。如果性能是您关心的问题,那么您可以放心地将其从您的脑海中排除,但最苛刻的计算场景除外
如果确实需要,可以通过实现shouldComponentUpdate()
方法避免重新呈现组件
这是不鼓励的:React正在朝着这个方向发展,您应该尽可能地使用它们。在这种情况下,您的工作是保证相同的道具将呈现相同的HTML。React的魔法引擎将完成剩下的工作。为什么您关心它的渲染频率?无用的重播只会降低性能