问题与react-router-dom有关。此链接与内部链接配合使用非常好,但是当我刷新或从外部打开url时,一切都不再起作用。
然后我发现自己面对白屏
我尝试使用hashHistory,它的效果要好得多。但是我不喜欢将#放在网址中间
路由器导轨
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
get :todos, to: "todos#index"
end
end
get '*path', to: "application#fallback_index_html", constraints: ->(request) do
!request.xhr? && request.format.html?
end
end
ApplicationController.rb
class ApplicationController < ActionController::API
def fallback_index_html
render :file => 'public/index.html'
end
end
我的React组件App.js
import React, { useState } from 'react';
import { Router, Switch, Route, Link } from 'react-router-dom';
import { createHashHistory } from 'history';
import './App.css';
const hashHistory = createHashHistory({});
function Home() {
console.log('Home');
return <p>Home <Link to="/gallery" >Gallery</Link></p>;
}
function Test() {
console.log('Home');
return <p>Home <Link to="/gallery" >Test</Link></p>;
}
function Config() {
console.log('Config');
return <p>Config</p>;
}
function Gallery() {
console.log('Gallery');
return <p>Gallery <Link to="/gallery/test" >Gallery-test</Link></p>;
}
function App() {
console.log('App');
const [todos, setTodos] = useState([]);
const fetchTodos = async () => {
fetch('/api/v1/todos')
.then(res => res.json())
.then(data => setTodos(data.todos));
};
return (
<Router history={hashHistory}>
<div className="App">
<header className="App-header">
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/config" component={Config} />
<Route exact path="/gallery" component={Gallery} />
<Route exact path="/gallery/test" render={() => <p>Nested Ntested</p>} />
</Switch>
<button onClick={fetchTodos}>FETCH</button>
<ul>
{
todos.map((todo, idx) => {
return <li key={idx} >{todo}</li>;
})
}
</ul>
</header>
</div>
</Router>
);
}
export default App;