React Router不渲染具有动态路径的组件

时间:2018-06-28 19:22:19

标签: javascript reactjs react-router

我对React还是很陌生,我正在尝试使用React和Contentful进行小型博客设置。这是我的代码:

Layout.js

import React, { Component } from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';
import * as contentful from 'contentful';
import Header from './Header/Header';
import Footer from './Footer/Footer';
import Home from './Content/Home/Home';
import About from './Content/About/About';
import Article from './Content/Home/Articles/Article';

class Layout extends Component {
  constructor(props){
    super(props);

    this.state = {
      spotlight: {
        title: 'test',
        path: '',
        subtitle: '',
        content: '',
      },
      posts: [],
    }
  }

...

  render() {
    const { title, subtitle, path, content } = this.state.spotlight;
    return (
      <div className='layout'>
        <Header />
        <Switch>
          <Route exact path='/'  component={Home}/>
          <Route path='/about' render={(match) => <About />}/>
          <Route path={`/${path}`} component={Article}/>
        </Switch>
        <Footer />
      </div>
    )
  }
}

export default withRouter(Layout);

Home.js

import React, {Component} from 'react';
import { Link, withRouter } from 'react-router-dom';
import * as contentful from 'contentful';
import Spotlight from './Spotlight/Spotlight';
import Article from './Articles/Article';

class Home extends Component { 
  constructor(props){
    super(props);

    this.state = {
      posts: [],
    };
  }


  render() {
    const { title, subtitle, path } = this.props;
    const { posts } = this.state;

    return (
      <div>      
        {posts.map(({fields}, i) => 
          <Link to={`/${fields.path}`} key={i}>
            <Spotlight key={i} title={fields.title} subtitle={fields.subtitle} />
          </Link>
          )}
      </div>
    )
  }
}

export default Home;

每当我单击链接并且页面为空白时,“布局”组件中的第三条路线都不会呈现“文章”组件。我是否正确地路由整个事情?

0 个答案:

没有答案