首页 > 解决方案 > React 路由器不会渲染组件

问题描述

我写了一小段代码来了解反应路由器,我已经设置了路由//aboutme并且/contact. 问题只是/路线有效,其他路线不会渲染。控制台中也没有错误,并且/路由可以正常工作localhost:8080/#!/localhost:8080/#!不正常工作,localhost:8080就像我想象的那样。我正在使用webpack 4来捆绑文件。我的配置文件是否有问题导致此问题? 我尝试在两种情况下都只渲染根组件来

访问路由throws cannot get/url throws cannot get/url
http://localhost:8080/#!/aboutme
http://localhost:8080/#!/contact


http://localhost:8080/aboutme
http://localhost:8080/contact

我不明白我做错了什么,请看一下。

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from 'react-router-dom'
import Route from 'react-router-dom/Route'

const root= (props) => {
    return (
        <p>hello</p>
    )
}
const about= (props) => {
    return (
        <p>About me -_-</p>
    )
}
const contact= (props) => {
    return (
        <p>contact info</p>
    )
}
const App = () => {
    return (
        <Router>
            <div>
                <Route path="/" exact component={root} />
                <Route path="/aboutme" exact component={about} />
                <Route path="/contact" exact component={contact} />
            </div>
        </Router>
    )
}

ReactDOM.render(<App />, document.getElementById("index"));

我的 webpack 配置

const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html"
});

module.exports = {
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index_bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  plugins: [htmlPlugin]
};

标签: javascriptreactjs

解决方案


使用<Switch />Component 为一个路由只渲染一个组件,并将确切的 prop 传递给 Route,它只有在匹配完整路径时才会渲染。

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Switch } from "react-router-dom";
import Route from "react-router-dom/Route";

const root = props => {
  return <p>hello</p>;
};

const about = props => {
  return <p>About me -_-</p>;
};

const contact = props => {
  return <p>contact info</p>;
};

const pageNotFound = props => {
  return <p>page not found.</p>;
};

const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/" exact component={root} exact />
        <Route path="/aboutme" exact component={about} exact />
        <Route path="/contact" exact component={contact} exact />
        <Route component={pageNotFound} />
      </Switch>
    </Router>
  );
};

ReactDOM.render(<App />, document.getElementById("index"));

推荐阅读