【问题标题】:React Router v4: Component and Children in the same routeReact Router v4:同一路由中的组件和子项
【发布时间】:2017-09-03 16:25:37
【问题描述】:

我是 react 的初学者,并且已经将基础项目升级到 react router v4。该应用程序似乎运行良好,但我总是收到以下警告:

警告:你不应该在同一路由中使用 将被忽略

这是我的应用程序(为了便于阅读,省略了一些导入):

index.js

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
        <BrowserRouter>{routes}</BrowserRouter>
    </Provider>
    , document.getElementById('root')
);

routes.js:

import {
  BrowserRouter as Router,
  Route,
  Switch,
  Link
} from 'react-router-dom';


export default (
    <Main>
      <Route path="/topics/create" component={CreateTopicView}> </Route>
      <Route path="/topics/search" component={SearchTopicsView}> </Route>
      <Route path="/topics/manage" component={ManageTopicsView}> </Route>
      <Route path="/moderation/pre" component={ModerationPreView}> </Route>
      <Route path="/moderation/post" component={ModerationPostView}></Route>
      <Route path="/dashboard" component={DashboardView}> </Route>
      <Route exact={true} path="/" component={DashboardView}> </Route>
    </Main>
);

ma​​in.js:

import PropTypes from 'prop-types'
import { withRouter } from 'react-router'


class Main extends React.Component {
    static propTypes = {
        match: PropTypes.object.isRequired,
        location: PropTypes.object.isRequired,
        history: PropTypes.object.isRequired
      }

    render() {
        let wrapperClass = "gray-bg " + this.props.location.pathname;
        return (
            <div id="wrapper">
                <Progress />
                <Navigation location={this.props.location}/>

                <div id="page-wrapper" className={wrapperClass}>

                    <TopHeader />

                    {this.props.children}

                    <Footer />

                </div>

            </div>

        )
    }
}


export default withRouter(Main)

这个想法是应该始终加载Main 组件中的大多数组件(例如Navbar),而且Navbar 需要知道当前路径,以便它可以显示当前选择。

那么TopHeaderFooter之间的变量内容应该根据路径显示出来。

我做错了什么,如何解决有关Route ComponentRoute Children 在同一路径中的警告?

【问题讨论】:

  • 那是因为您的路线之间有空间。在 v4 中表现为子级和路由不应该有子级&lt;Route path="/topics/create" component={CreateTopicView}&gt;{/* you have space here */}&lt;/Route&gt;
  • @ShubhamKhatri 哇,解决了,谢谢!
  • @Mustika 您应该将此作为答案发布并接受它,以便其他人可以看到您的问题已解决。

标签: reactjs react-router


【解决方案1】:

正如 Shubham Khatri 在评论中提到的,警告是由我在路线开始标签后的空格引起的:

那是因为您的路线之间有空间。它表现为 v4 中的子节点和路由不应该有子节点 {/* 你有空间 这里 */}

将路由定义更改为

<Route path="/topics/create" component={CreateTopicView}></Route>

<Route path="/topics/create" component={CreateTopicView} />

修正了警告

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-08
    • 2019-04-12
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    相关资源
    最近更新 更多