Случайная строка запроса появляется в реакторе-маршрутизаторе

Выглядит очень странно, когда я открываю /, браузер будет отображать что-то вроде /#/?_k=dlo2cz в адресе. Значение строки случайного запроса изменяется каждый раз, когда я обновляю страницу или переключаюсь на другой маршрут.

введите описание изображения здесь

Код был скопирован и вставлен и на react-router branch 1.0.0-rc1.

import React from 'react';
import { Router, Route, Link, IndexRoute } from 'react-router';


const App = React.createClass({
  render() {
    return (
      <div>
        <h1>App</h1>
        {/* change the <a>s to <Links>s */}
        <ul>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/inbox">Inbox</Link></li>
        </ul>

        {/*
          next we replace `<Child>` with `this.props.children`
          the router will figure out the children for us
        */}
        {this.props.children}
      </div>
    )
  }
});

const Message = React.createClass({
  render() {
    return <h3>Message</h3>
  }
});
const About = React.createClass({
  render() {
    return <h3>About</h3>
  }
});

const Inbox = React.createClass({
  render() {
    return (
      <div>
        <h2>Inbox</h2>
        {/* Render the child route component */}
        {this.props.children || "Welcome to your Inbox"}
      </div>
    )
  }
})


// Finally, we render a <Router> with some <Route>s.
// It does all the fancy routing stuff for us.
React.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
      <Route path="inbox" component={Inbox}>
        {/* Add the route, nested where we want the UI to nest */}
        <Route path="messages/:id" component={Message} />
      </Route>
    </Route>
  </Router>
), document.body);

Ответы

Ответ 1

Чтобы избежать этого, вы можете установить queryKey в false при создании browserHistory. Следующий пример иллюстрирует, что

import { Router, Route, BrowserHistory } from 'react-router';

let bHistory = BrowserHistory({
  queryKey: false
});

  <Router history={bHistory}>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
      <Route path="inbox" component={Inbox}>
        {/* Add the route, nested where we want the UI to nest */}
        <Route path="messages/:id" component={Message} />
      </Route>
    </Route>

Для React-router v2.0.0

import { Router, useRouterHistory } from 'react-router'
import { createHashHistory } from 'history'
const appHistory = useRouterHistory(createHashHistory)({ queryKey: false })
<Router history={appHistory}/>

Update:

С текущей версией React-router вам не нужно устанавливать модуль history npm отдельно. Он будет автоматически установлен как зависимость при установке реактивного маршрутизатора.

Если вы получите предупреждение:

Warning: Using { queryKey: false } no longer works. Instead, 
just don't use location state if you don't want a key in your URL query string.

или queryKey : false не работает.

Тогда может случиться так, что у вас может быть несовместимая версия истории с реактивным маршрутизатором. Просто проверьте, установлен ли модуль истории отдельно, если это так, то удалите его. Выше предупреждение исчезнет.

Изменить: для получения точных зависимостей

Если вы хотите узнать, какие зависимости требуется вашему "реагирующему маршрутизатору", проверьте пакет .json на github или вы можете попробовать выполнить следующую команду.

$ npm info "[email protected]" dependencies

{ 
   history: '^2.1.2',
  'hoist-non-react-statics': '^1.2.0',
   invariant: '^2.2.1',
   warning: '^3.0.0',
  'loose-envify': '^1.2.0' 
}

Ответ 2

Это ссылка на состояние местоположения, она документировала здесь: Если вы хотите избавиться от него, вам понадобится другое хранилище для вашей истории, такое как API истории браузеров, например:

import createBrowserHistory from 'history/lib/createBrowserHistory';    
<Router history={createBrowserHistory()}>