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

时间:2016-04-27 14:30:55

标签: javascript reactjs react-router

我使用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组件。如果我删除&#34; history = {appHistory}&#34;部分来自路由器组件,然后它呈现MyTable组件。我也尝试使用路由器中的默认browserHistory,同样的事情 - 不使用历史属性,没有它就可以工作。

我做错了什么?

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

2 个答案:

答案 0 :(得分: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,它将无效。

答案 1 :(得分:0)

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