1. ホーム
  2. javascript

[解決済み] React-router v4 - GET *url* できない

2023-01-05 02:08:21

質問

react-router v4を使い始めたのですが、シンプルな <Router> をapp.jsに記述し、いくつかのナビゲーションリンクを設定しています(以下のコードを参照)。もし私が localhost/vocabulary に移動すると、ルーターは私を正しいページにリダイレクトします。しかし、その後リロード(F5)を押すと、( localhost/vocabulary ) を押すと、すべてのコンテンツが消え、ブラウザは Cannot GET /vocabulary . どのようにそれは可能ですか?誰かが私にそれを解決する(ページを正しく再ロードする)方法の手がかりを与えることができますか?

App.jsです。

import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { Switch, Redirect } from 'react-router'
import Login from './pages/Login'
import Vocabulary from './pages/Vocabulary'

const appContainer = document.getElementById('app')

ReactDOM.render(
  <Router>
    <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/vocabulary">Vocabulary</Link></li>
        </ul>
        <Switch>
          <Route exact path="/" component={Login} />
          <Route exact path="/vocabulary" component={Vocabulary} />
        </Switch>
    </div>
  </Router>,
appContainer)

どのように解決するのですか?

Webpackを使用していると仮定します。もしそうなら、webpack の設定にいくつかのことを追加することで問題が解決するはずです。具体的には output.publicPath = '/'devServer.historyApiFallback = true . 以下は、この両方を使用した webpack の設定例で、私の場合は更新の問題が解決しました。もし、あなたが好奇心旺盛なら、"なぜ"。 この が役に立ちます。

var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index_bundle.js',
    publicPath: '/'
  },
  module: {
    rules: [
      { test: /\.(js)$/, use: 'babel-loader' },
      { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
    ]
  },
  devServer: {
    historyApiFallback: true,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'app/index.html'
    })
  ]
};

これについては、こちらに詳しく書きました -。 React Routerで更新時の"cannot GET"エラーを修正する(またはクライアント側ルータの仕組み)。