React路由器不呈现组件?

时间:2017-12-12 00:54:36

标签: reactjs react-router

我尝试渲染新组件而不显示原始主组件。我分离了我的组件,现在当我尝试将它们渲染出来时,它没有显示出来。

class App extends Component {
render() {
return (
  <div>
      <Route exact={true} path="/" component={Home} />
  </div>
);
}
}

这是我的主组件,它应该呈现About组件和Pages组件,但是当我点击它时它不会显示任何内容。

const Home = () => (
<div>
    <h2>Home page</h2>
    <div>
        <ul>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/pages">Page with Subpages</Link></li>
        </ul>
        <Route path="/about" component={About} />
        <Route path="/pages" component={Pages} />
    </div>
</div>
)

我的关于组件:

const About = () => (
<div>
    <h2>About page</h2>
</div>
)

我的网页组件:

const Pages = ({ match }) => (
<div>
    <h2>Page with Subpages</h2>
    <ul>
        <li><Link to={`${match.url}/subpage1`}>Subpage 1</Link></li>
        <li><Link to={`${match.url}/subpage2`}>Subpage 2</Link></li>
        <li><Link to={`${match.url}/subpage3`}>Subpage 3</Link></li>
    </ul>

    <Route path={`${match.url}/subpage1`} component={Subpage1}/>
    <Route path={`${match.url}/subpage2`} component={Subpage2}/>
    <Route path={`${match.url}/subpage3`} component={Subpage3}/>
</div>
)

2 个答案:

答案 0 :(得分:1)

我认为,您应该从exact删除<Route path="/" component={Home} />,因为在您的情况下,您将Home和Pages组件放在Home下,所以当您转到/about网址时,没有主页组件,因为你把exact放在那里,所以你看到一个空白的屏幕;

class App extends React.Component {
  render() {
    return (
      <div>
        <Route path="/" component={Home} />
      </div>
  );
  }
}

这里有完整的工作示例:https://codesandbox.io/s/mjr8xypp4x

答案 1 :(得分:1)

您必须忘记添加<Router> <BrowserRouter>组件,该组件必须作为主要组件嵌入到定义了主Route的类组件中,

这是解决方案 -

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

class Appz extends React.Component {
    render() {
      return (
        <Router>
         <div>
           <ul>
            <li><Link to="/about">Home</Link></li>
           </ul>
           <div>
            <Route path="/" component={Home} />
           </div>
          </div>
        </Router>
      );
    }
}

const Home = () => (
  <div>
    <h2>Home page</h2>
    <div>
      <ul>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/pages">Page with Subpages</Link></li>
      </ul>
      <Route path="/about" component={About} />
      <Route path="/pages" component={Pages} />
    </div>
  </div>
)

const About = () => (
  <div>
    <h2>About page</h2>
  </div>
)

const Pages = ({ match }) => (
  <div>
    <h2>Page with Subpages</h2>
    <ul>
      <li><Link to={`${match.url}/subpage1`}>Subpage 1</Link></li>
      <li><Link to={`${match.url}/subpage2`}>Subpage 2</Link></li>
      <li><Link to={`${match.url}/subpage3`}>Subpage 3</Link></li>
    </ul>


  </div>
)

export default Appz;

工作示例 - https://codesandbox.io/s/kxmj48p14v