React-router 在添加历史记录后不会渲染组件

React-router doesn't render component after adding history

本文关键字:组件 添加 历史 记录 React-router      更新时间:2023-09-26

我正在使用 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 组件。如果我从路由器组件中删除"history={appHistory}"部分,那么它会呈现 MyTable 组件。我还尝试使用默认浏览器路由器的历史,同样的事情 - 不适用于历史属性,没有它就可以工作。

我做错了什么?

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

确保你的路径是正确的!例如:如果您将 path 设置为 - path="/"并且您的域是example.com的 - 并且您正在使用 react on 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如果您在此处设置任何其他字符串,它将不起作用。

这里可能有一些事情,但我会尝试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'));