React-Router如何链接到实际页面的链接

时间:2017-12-28 22:29:09

标签: javascript reactjs react-router

编辑:我发现当直接这样做时,浏览器会尝试找到名为"定价"的文件,如何让浏览器不这样做并查找index.html?我在webpack-dev-server上运行

Edit2:我现在得到了一点,我想链接localhost:8080 / price直接转到index.html然后运行路由器并进入定价组件,我该怎么做?

我在网站上设置了React-Router,但是当直接访问特定页面时(例如:localhost:8080 / pricing),它会给我以下错误:

Content Security Policy: The page’s settings blocked the loading of a resource at blob:http://localhost:7080/685880ef-cf95-4ccf-a6f6-3d8c182ee941 (“default-src http://localhost:7080”).
Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src http://localhost:7080”). Source: ;(function installGlobalHook(window) {...

这是我的页面代码

ReactDOM.render(
  <BrowserRouter>
    <App/>
  </BrowserRouter>
    ,
  document.getElementById('app'));

export default class App extends React.Component {
  render(){
    return (
      <div>
        <Header/>
        <Body/>
        <Footer/>
      </div>
    );
  }
} 

class Body extends React.Component {
  render(){
    return (
      <Switch>
        <Route exact path='/' component={Home}/>
        <Route path='/pricing' component={Pricing}/>
        <Route path='/contactus' component={ContactUs}/>
        <Route path='/buy' component={Buy}/>
      </Switch>
    );
  }
}

请注意,如果我直接访问主页,如果我转到localhost:8080然后使用我的链接在其他页面之间导航

1 个答案:

答案 0 :(得分:2)

我想问题出在你的webpack配置上,你需要将historyApiFallback添加到devServer部分:

此配置可让您直接转到定价页面。

devServer: {
  historyApiFallback: true,
  host: '0.0.0.0',
  hot: true,
  port: 3000
}

或在您的scripts部分(在 package.json 文件中):

"scripts": {
  "start": "webpack-dev-server --history-api-fallback"
}

检查this以查看文档。