【问题标题】:React-router doesn't render component after adding history添加历史记录后,React-router 不渲染组件
【发布时间】:2016-08-21 22:21:31
【问题描述】:

我将 React 与 React Router 一起使用,我有一个非常简单的案例:

var Router = window.ReactRouter.Router;
var useRouterHistory = window.ReactRouter.useRouterHistory;
var Route = window.ReactRouter.Route;
var createHistory = window.History.createHistory;
const appHistory = useRouterHistory(createHistory)({ queryKey: false });

// my component ...

ReactDOM.render((
  <Router history={appHistory}>
    <Route path="/" component={MyTable}>
    </Route>
  </Router>
), document.getElementById('table-wrapper'));

但是,这不会呈现 MyTable 组件。如果我从 Router 组件中删除“history={appHistory}”部分,那么它会呈现 MyTable 组件。我还尝试使用路由器中的默认 browserHistory,同样的事情 - 不适用于历史属性,没有它也可以。

我做错了什么?

编辑:控制台中没有错误消息,我使用的是非缩小的 React 开发版本。

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    确保你的路径是正确的!例如:如果您将路径设置为 - path="/" 并且您的域是 example.com - 并且您在 example.com/someanothepath 上使用反应 - 您的路径将无法正常工作。

    这是jsffidle上的示例

    var 
        useRouterHistory = ReactRouter.useRouterHistory,
        createHistory = History.createHistory,
        Router = ReactRouter.Router,
        Route = ReactRouter.Route;
    
    const appHistory = useRouterHistory(createHistory)({ queryKey: false });
    var MyTable = React.createClass({
        render: function() {
    
            return (
                <div className="test">
                    table
                </div>
            )
        }
    });
    
    
    ReactDOM.render((
      <Router history={appHistory}>
        <Route path="/_display" component={MyTable}>
        </Route>
      </Router>
    ), document.getElementById('table-wrapper'));
    

    如您所见 - jsfiddle 路径为 /_display 如果您在此处设置任何其他字符串,它将不起作用。

    【讨论】:

    • 谢谢,成功了。它仅在没有历史属性的情况下与 '/' 一起使用(这让我感到困惑 - 为什么它会起作用?)但对于历史却没有。但是,我曾希望使用此 appHistory 会从 URL 中删除 _k 查询字符串,但它没有。
    【解决方案2】:

    这里可能有一些东西,但我会尝试createHashHistory 而不是createHistory

    const Router = window.ReactRouter.Router;
    const useRouterHistory = window.ReactRouter.useRouterHistory;
    const Route = window.ReactRouter.Route;
    const createHashHistory = window.History.createHashHistory;
    const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });
    
    // my component ...
    
    ReactDOM.render((
      <Router history={appHistory}>
        <Route path="/" component={MyTable} />
      </Router>
    ), document.getElementById('table-wrapper'));
    

    【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2023-03-08
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    相关资源
    最近更新 更多