首页 > 解决方案 > React Route Path 显示空白页面

问题描述

我正在尝试在 Main 中获取 Singleshow 并在指定路径中显示文本

单秀 index.js

import React, { Component } from 'react';

class SingleShow extends Component {
    render () {
        return (
            <div>
                <p>Single Shows</p>
            </div>
        )
    }
}

export default SingleShow;

主索引.js

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Shows from '../Shows';
import SingleShow from '../SingleShow';

const Main = props => (
    <Switch>
        <Route exact path="/" component={Shows} />
        <Route path="/shows/:id" component={SingleShow} />
    </Switch>
);

export default Main;

路由确切路径完美运行,但是当我http://localhost:3000/shows/123在浏览器中输入时,我得到一个空页面。

当我在 Chrome 中检查时,我只看到两件事:

标签: reactjsreact-router

解决方案


您应该在 SingleShow 组件中使用构造函数

constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { id:this.props.match.params.id};
}

然后在渲染

render () {
    return (
        <div>
            <p>{this.state.id}</p>
        </div>
    )
}

推荐阅读