React Router 不加载外部 html 文件

React Router doesn`t load external html files

我正在使用 react + react-router 构建一个 React 应用程序,但我对重定向有疑问。

我有下一个文件夹结构:

... /public /index.html (react index) /tos/ /terms.html /privacy.html ... /src index.js App.js ...

index.js:

class App extends Component {

    render() {
        return (
            <Router>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/settings" component={Settings}/>
                </Switch>
            </Router>
        )
    }
}

ReactDOM.render(<App/>, document.getElementById('root'));
registerServiceWorker();

问题是当我想重定向到 /public/tos/terms.html/public/tos/privacy.html 时,有时(在 chrome 中更频繁),我不能。项目再次呈现索引,并显示空白页面,因为路由 /public/tos/terms.html/public/tos/privacy.html 未在路由开关中声明。

另一方面,我在同一个 base_url 中还有其他 "no-react" 项目,但在其他端口 www.my-project.com:4040/other 中监听,我已在下一条路线中配置它:www.my-project.com/other。但在这种情况下,我遇到了同样的问题,当我从我的 React-app 重定向到这条路线时,react 不重定向并再次渲染没有内部组件的 App.js

有人可以告诉我任何重定向到同一项目中的其他地方但没有反应的方法吗?

如果你试图达到有效 url /public/tos/terms.html 你必须有组件来处理 url :

<Route  path="/public/tos/terms" component={/*Component to render*\ }/>

所以它会像:

        <Router>
          <div>
            <Switch>
                <Route path="/settings" component={Settings}/>
                <Route  path="/public/tos/terms" component={/*Component to render*\ }/>
                <Route exact path="/" component={Home}/>
            </Switch>
          </div>
        </Router>

如果您正在寻找如何将外部文件作为组件包含在您的 reactjs 中,那么其中一种方法是,使用 axios and then you can use it as dangerouslySetInnerHTML

发送获取请求
function getExternalFile(fileName) {
   const request = axios.get('/myAPI/getExternalFile/' + fileName).then(
    respone =>
     {this.setState({externalFile: response})}); }

function MyComponent() {
  return <div dangerouslySetInnerHTML={getHTMLFile()} />;
}

在您的应用上下文中,"Redirect" 是什么意思?

如果你想简单地从你的页脚 Link 到那些静态页面,使用简单的 HTML 锚点 / link 标签而不是 React Router Link 组件.

例如:

const Footer = () => 
 <div>
   <a href='/tos/terms.html'>Terms and Conditions</a>
   <Link to='/login'>Sign in</Link>
 </div>

第一个 link 将由浏览器处理,应该可以正常工作。第二个将由 React Router 处理,并且应该与您的路由配置中的路由匹配。

如果你真的想 redirect,比如用户访问 url A 但我希望它最终登陆 url B,然后显示更多代码。 ;)

我认为你的问题与 ReactRouter 无关...RR 在 Google Chrome 以及其他浏览器中工作。查看您的应用程序中是否有 registerServiceWorker,因为这可能是 Chrome 中的重定向错误。如果您拥有它但不用于其他用途,请将其删除。

希望对您有所帮助。