【问题标题】:React Router Component not Rendering反应路由器组件不渲染
【发布时间】:2017-12-23 17:40:08
【问题描述】:

我一直在使用 React Router 并尝试将我的 App.js 和 Car.js 组件一起路由。我在这两个组件中写了 {this.props.children} 但它仍然无法正常工作。当我部署我的应用程序时,我的本地主机页面上没有任何地方显示 Car.js 组件的任何指示。

这是我的 App.js:

import React, { Component } from 'react';
import Login from './Login.js';
import Search from './Search.js';
import Message from './Message.js';
import Car from './Car.js';
import {BrowserRouter, Route} from 'react-router-dom';

export default class App extends React.Component {
  render() {
    return (
      <div>
        <Login />
        <Search />
        <Message />
            <div>
                <BrowserRouter> 
                <Route path="/Car" component={Car}/>
                </BrowserRouter>
                {this.props.children}
            </div>
      </div>

    );
  }
}

Car.js:

// Car page example 
import React, { Component } from 'react';
import {Router, Route} from 'react-router';

class Car extends Component {
    render(){
        return(
            <div>
                <h1> Cars page </h1>
                {this.props.children}
            </div>
        );
    }
}

export default Car;

【问题讨论】:

  • 不需要this.props.children,只有访问相应的url才会执行Route
  • 本例中也不需要类组件。

标签: javascript reactjs components react-router render


【解决方案1】:

因此,您至少需要 2 条路线,除非 /Cars 是唯一的页面,在这种情况下您不需要路线! :)

在此示例中,当您的 url 类似于 http:/www.exmaple.com/ 时,将显示 Home 组件

当url为http:/www.exmaple.com/Cars时会显示Cars组件

const App = () => (
    <div>
        <Login />
        <Search />
        <Message />
        <div>
            <BrowserRouter>
                // you're going to want a default view
                <Route exact path="/" component={Home} />
                // this will be displayed when your url has /Car at the end of it
                <Route path="/Car" component={Car} />
            </BrowserRouter>
        </div>
    </div>
);

如果您不想手动输入网址来更改视图...您将必须包含指向相应视图的&lt;Link /&gt;&lt;NavLink /&gt;

试试&lt;NavLink to="/Cars" /&gt;,别忘了加上{ ... NavLink ... } from "react-router-dom"

您可能想在 ReactTraining.com's react-router 页面上查看 react-router WEB documentation。他们是创建和维护react-router 的人。文档也很好!

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 2023-04-03
    • 2018-06-02
    • 1970-01-01
    • 2016-02-24
    • 2022-10-23
    • 2020-01-08
    • 2021-04-24
    • 2019-04-25
    相关资源
    最近更新 更多