【问题标题】:What's the better way to configure routes in App.js in React with react-router-dom在 React 中使用 react-router-dom 在 App.js 中配置路由的更好方法是什么
【发布时间】:2021-04-14 16:03:53
【问题描述】:
在 React 的 App.js 中,我们可以:
<div className="App">
<Router>
<Switch>
<Route
path="/basics"
>
<BasicsPage></BasicsPage>
</Route>
// other routes
</Switch>
</Router>
</div>
或
<div className="App">
<Router>
<Switch>
<Route
path="/basics"
component={BasicsPage}
>
</Route>
// other routes
</Switch>
</Router>
</div>
只是想知道哪种写法更好,两者之间是否有任何区别?谢谢!
【问题讨论】:
标签:
javascript
reactjs
react-router-dom
【解决方案1】:
第二种方案是最好的,主要是因为它为组件提供了matches props。
Here is a codesandbox exemple.(检查index.js文件而不是包含路由)
但每个解决方案都是有用的。
如果您想将道具传递给BasicPage,第一种方法最好添加您想要的所有道具。
但是,如果您可以选择,请使用第二种解决方案,该解决方案对您的应用的未来更易于维护和清洁。
如果您需要提供您的自定义道具和react-router 给出的道具,您可以使用第三种解决方案:
<Route exact path="/" render={(props) => <App matches={props} myProps={1} />} />
【解决方案2】:
这取决于您是否想要/需要将route props(history、location 和 match)传递给组件。
<div className="App">
<Router>
<Switch>
<Route
path="/basics"
component={BasicsPage} // <-- route props passed
/>
<Route
path="/basics"
>
<BasicsPage /> // <-- route props not passed
</Route>
// other routes
</Switch>
</Router>
</div>
但是,如果您需要将额外的 props 传递给组件,那么第二种方法允许这样做。
<div className="App">
<Router>
<Switch>
<Route
path="/basics"
>
<BasicsPage myCustomProp={someValue} /> // <-- pass custom prop
</Route>
// other routes
</Switch>
</Router>
</div>
如果您需要路由道具和来传递额外的道具,请使用render 道具。
<div className="App">
<Router>
<Switch>
<Route
path="/basics"
render={routeProps => (
<BasicsPage
{...routeProps} // <-- pass route props
myCustomProp={someValue} // <-- and pass custom prop
/>
)}
/>
// other routes
</Switch>
</Router>
</div>
【解决方案3】:
Route render methods:
推荐 使用<Route> 渲染内容的方法是使用children 元素,如下所示。但是,您可以使用其他一些方法(请参阅this)使用<Route> 渲染某些东西。这些主要用于支持在引入钩子之前使用早期版本的路由器构建的应用程序。
示例:
<Router>
<Switch>
<Route path="/basics">
<BasicsPage />
</Route>
<Route path="/foo">
<Foo>Some children here</Foo>
</Route>
</Switch>
</Router>
使用上述方法声明所有路由并使用hooks(useHistory、useLocation、useParams 等)访问路由器的内部状态。这种风格也可以很容易地切换到React Router v6。请参阅@jonrsharpe 在comment 中指出的this。