刷新时未加载页面-react-router-dom

时间:2018-07-27 22:17:18

标签: javascript reactjs react-router-dom

我有以下页面的基本应用程序:主页,个人资料,联系方式和经验。我已经为每个页面设置了路由,但是当我转到首页以外的其他页面时,它会呈现,但是当我刷新页面时,该页面不会加载。

我注意到是否在页面名称之前添加了#,例如页面呈现的http://localhost:1234/#/profile。因此,我很困惑为什么我需要使用我不需要的#,而我正在使用react-router-dom,所以不需要#

我将historyApiFallback添加到了我的webpack.config中,但这不起作用。谁能帮我这个?我是新来的反应者,我想学习更多。您的帮助将不胜感激!

App.jsx

import React, { Component } from "react";
import Navbar from "./components/navbar";
import Intro from "./components/introPage";
import Experience from "./components/experiencePage";
import Profile from "./components/profilePage";
import Contact from "./components/contactPage";
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';

class App extends Component {
    render(){
        return (
            <Router>
                <div className="pageSections">
                    <Navbar />
                    <div className="navContent">
                        <Route exact path="/" component={Intro}/>
                        <Route path="/experience" component={Experience}/>
                        <Route path="/profile" component={Profile}/>
                        <Route path="/contact" component={Contact}/>
                    </div>
                </div>
            </Router>
        );
    }
}

export default App;

navbar.jsx

import React, { Component } from "react";
import { Link } from "react-router-dom";

class Navbar extends Component {
    render(){
        return (

            <div className="navFrame">
                <Link to="/">
                    <div className="topNav"><div className="navBar"><h3>Marteen</h3></div></div>
                </Link>

                <Link to="/profile">
                    <div className="rightNav"><div className="navBar"><h3>Profile</h3></div></div>
                </Link>

                <Link to="/experience">
                    <div className="bottomNav"><div className="navBar"><h3>Experience</h3></div></div>
                </Link>

                <Link to="/contact">
                    <div className="leftNav"><div className="navBar"><h3>Contact</h3></div></div>
                </Link>
            </div>

        );
    }
}

export default Navbar;

webpack.config.js

const webpack = require('webpack');
const config = {
    entry:  __dirname + '/js/index.jsx',
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js',
    },
    resolve: {
        extensions: ['.js', '.jsx', '.css']
    },
    module: {
      rules: [
        {
          test: /\.jsx?/,
          exclude: /node_modules/,
          use: 'babel-loader'
        },
        {
          test: /\.scss?/,
          loader: 'style-loader!css-loader!sass-loader' 
        }
      ]
    },
    devServer: {
        historyApiFallback: true,
        contentBase: './',
        hot: true
    }
};
module.exports = config;

package.json

{
  "main": "index.js",
  "scripts": {
    "build": "webpack -p --progress --config webpack.config.js",
    "dev-build": "webpack --progress -d --config webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --progress -d --config webpack.config.js --watch",
    "start": "npm run open",
    "open": "concurrently \"http-server -a localhost -p 1234\" \"open http://localhost:1234\""
  },

  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "concurrently": "^3.6.1",
    "css-loader": "^0.28.11",
    "http-server": "^0.11.1",
    "node-sass": "^4.7.2",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "sass-loader": "^6.0.7",
    "style-loader": "^0.20.3",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.12"
  },
  "dependencies": {
    "npm": "^5.10.0"
  }
}

更新

enter image description here

package.json

{
  "name": "fullstack_profile",
  "version": "1.0.0",
  "description": "fullstack profile with flask and react",
  "main": "index.js",
  "scripts": {
    "build": "webpack -p --progress --config webpack.config.js",
    "dev-build": "webpack --progress -d --config webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack-dev-server --hot --progress --mode development",
    "start": "npm run open",
    "open": "concurrently \"http-server -a localhost -p 1234\" \"open http://localhost:1234\""
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/medev21/fullstack_profile.git"
  },
  "author": "martin",
  "babel": {
    "presets": [
      "es2015",
      "react"
    ]
  },
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/medev21/fullstack_profile/issues"
  },
  "homepage": "https://github.com/medev21/fullstack_profile#readme",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "concurrently": "^3.6.1",
    "css-loader": "^0.28.11",
    "http-server": "^0.11.1",
    "node-sass": "^4.7.2",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "sass-loader": "^6.0.7",
    "style-loader": "^0.20.3",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.12",
    "webpack-dev-server": "^3.1.5"
  },
  "dependencies": {
    "npm": "^5.10.0"
  }
}

webpack.config

const webpack = require('webpack');
const config = {
    entry:  __dirname + '/js/index.jsx',
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js',
    },
    resolve: {
        extensions: ['.js', '.jsx', '.css']
    },
    module: {
      rules: [
        {
          test: /\.jsx?/,
          exclude: /node_modules/,
          use: 'babel-loader'
        },
        {
          test: /\.scss?/,
          loader: 'style-loader!css-loader!sass-loader' 
        }
      ]
    },
    devServer: {
      contentBase: __dirname + '/dist',
      compress: false,
      port: 1234,
      historyApiFallback: {
        index: 'index.html'
      }
    }
};
module.exports = config;

enter image description here

2 个答案:

答案 0 :(得分:2)

http://localhost:1234/#/profile起作用的原因是因为#不会重新加载页面。它的行为与您在同一页面上但滚动到页面的特定部分的HTML中的定位标记相同。例如,下面将您滚动到页面的投资组合部分。

<a href="www.page.com/#portfolio">Portfolio</a>

如果省略#,则有所不同。这告诉您的服务器重新加载页面并访问该位置。对于您来说,http://localhost:1234/profile对于服务器来说是未知的,因为您没有在服务器端指定它。在这种情况下,您需要创建路由或在找不到路由时代理请求。

在使用作为客户端路由器的react-router时,服务器需要提供相同的文件,因此应该使用proxy选项。

使用http-server the docs时,可以添加-P或--proxy标志来指定它。

  

-P或--proxy代理所有无法在本地解析为给定URL的请求。例如:-P http://someurl.com

在您的情况下,请在package.json中更新以下内容。

"open": "concurrently \"http-server -a localhost -p 1234 -P http://localhost:1234\" \"open http://localhost:1234\""

一种替代方法是使用webpack-dev-server进行开发。当组件发生更改时,它支持热重装,它将大大改善您的开发人员体验。

使用npm install --save-dev webpack-dev-server

安装

将以下内容添加到您的webpack配置中。

devServer: {
  contentBase: __dirname + '/dist',
  compress: false,
  port: 1234,
  historyApiFallback: {
    index: 'index.html' // assuming this is your entry point file that loads your bundle.
  }
},

然后在package.json中为其添加脚本并使用npm run watch

运行它
"watch": "webpack-dev-server --hot --progress --mode development",

注意:请确保在您的dist文件夹index.html中存在。如果不是,则会遇到问题。

我创建了一个basic project on GitHub,所以您有一个可行的示例。

答案 1 :(得分:0)

Express和至少Heroku部署的解决方案

我想分享我的解决方案,最终使用户可以访问我的React App中的每个链接。

在阅读了这些建议的解决方案和this helpful article之后,我可以设法在主server.js主文件中使用以下代码来实现此目的:

// Serve static files such as images, CSS files, and JavaScript files for the React frontend app
app.use(express.static(path.join(__dirname, 'client/build')))
// This solves the "Not found" issue when loading an URL other than index.html.
app.get('/*', (req, res) => { //n3
  res.sendFile(path.join(__dirname + '/client/build/index.html'), err => {
    if (err) { res.status(500).send(err) }
  })
})
  • 确保始终指向构建路径,这是在生产环境中加载所有文件的位置。
  • 之后,所有网址最终都运行良好!