exact 和 render 都是 React Router 中常用的 props。
exact 是用于匹配路径时精确匹配的,如果没有设置 exact,则在路径匹配时会出现模糊匹配的情况。举个例子,我们定义了两个路由:
<Route path="/product" component={Product} />
<Route path="/product/detail" component={ProductDetail} />
如果用户访问 "/product/detail" 路径时,如果没有设置 exact,它首先匹配到的是 "/product" 这个路由,因为 "/product" 这个路径也包含了 "/product/detail",这就导致了路径不匹配的问题。因此,我们需要在 "/product" 路由上设置 exact 属性, 防止路径模糊匹配的问题出现。
<Route path="/product" exact component={Product} />
render 负责渲染路由的组件,跟 component 类似,只是它接收到的是一个函数,而不是组件。
<Route path="/" render={() => <div>这是首页</div>} />
这里的 render 接收一个函数,函数返回一个组件。它的优点在于可以根据需要使用内联函数,而不需要编写另一个组件,这样可以减少代码的复杂度。当然,使用 render 也有一个劣势,就是它不能像 component 一样继承路由的 props,需要手动传递。
如下所示,component 语法自动将 history, location 和 match 作为props传递到组件,而 render 情况下需要我们手动传递:
<Route path='/' component={Home} />
<Route path='/about' render={(props) => (
<About {...props} isAuthed={true} />
)} />