反应组件和渲染之间的路由器差异 [英] react router difference between component and render
问题描述
我真的不明白在反应路由器的路由中渲染和组件道具之间的区别,在文档中它说渲染不会创建新元素但组件会,我试图回顾历史,但我发现 componentWillMount 是当我在 Route 中使用 render 时调用,它们是什么意思如果您为组件属性提供内联函数,您将在每次渲染时创建一个新组件.这会导致现有组件卸载并安装新组件,而不仅仅是更新现有组件."
I really don't get the difference between render and component prop in Route in react router, in docs it says that render doesn't create new element but component does, I tried to go back with history but I found componentWillMount is called when I use render in Route, what do they mean by "if you provide an inline function to the component attribute, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component."
推荐答案
源代码说明了区别:
if (component)
return match ? React.createElement(component, props) : null
if (render)
return match ? render(props) : null
当您使用 component
属性时,每次调用 Route#render
都会对组件进行实例化.这意味着,对于您传递给路由的 component
属性的组件,构造函数、componentWillMount
和 componentDidMount
将在每次路由时执行呈现.
When you use component
prop, the component is instantiated per every call of Route#render
. It means that, for your component that you pass to component
prop of Route, constructor, componentWillMount
, and componentDidMount
will be executed every time the route is rendered.
例如,如果你有
<Route path="/:locale/store" component={Store} />
并且用户导航到/en/store,然后转到其他地方,然后导航回/en/store,Store组件将被挂载,然后卸载,然后再次挂载.这类似于做
and the user navigates to /en/store, then goes elsewhere, and then navigates back to /en/store, the Store component will be mounted, then unmounted, and then mounted again. It is similar to doing
<Route path="/:locale/store">
<Store />
</Route>
相比之下,如果您使用 render
属性,则组件会在每个 Route#render
上评估.还记得每个组件都是一个函数吗?此函数将按原样执行,没有任何生命周期方法.所以当你拥有它时
Compared to that, if you use render
prop, the component is evaluated on every Route#render
. Remember that every component is a function? This function will be executed as is, without any lifecycle methods. So when you have it like
<Route path="/:locale/store" render={Store} />
你可以把它想象成
<Route path="/:locale/store">
{Store()}
</Route>
它节省了你的运行时间,因为没有运行生命周期方法,但它也有一个缺点,如果 Store 组件有一些 post-mount 生命周期方法,比如 shouldComponentUpdate 也可以提高性能.
It saves you runtime because no lifecycle methods are run, but it also has a downside in case Store component has some post-mount lifecycle methods like shouldComponentUpdate that may increase performance as well.
有一篇关于这种性能的好帖子hack,请看一下.写得很好,也适用于 React 16.
There was a good post on Medium about this performance hack, please take a look at it. It's written very well and is applicable to React 16, too.
这篇关于反应组件和渲染之间的路由器差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!