簡體   English   中英

React Router不會渲染組件

[英]React router wont render components

我寫了一小段代碼來了解React Router,我已經設置了路由//aboutme/contact 問題是僅/路由有效,其他路由無法渲染。 控制台中也沒有錯誤,並且/路由在localhost:8080/#!/localhost:8080/#! 不是我想的那樣在localhost:8080 我正在使用webpack 4捆綁文件。 我的配置文件有問題嗎?

我嘗試在訪問路線
http://localhost:8080/#!/aboutme
http://localhost:8080/#!/contact
在兩種情況下,僅渲染根組件

http://localhost:8080/aboutme引發無法獲取/ URL
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] }; 

使用<Switch />組件僅渲染一條路線的一個組件,並將精確的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"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM