首页 文章

我无法以编程方式更改react-router中的路由

提问于
浏览
0

我正在尝试在创建模型后以编程方式重定向到新的路由/组件 . <Link> 组件按预期工作 . 我正在使用MobX . 这在我使用Redux之前就已经开始了 . 当我搬到MobX时,它停止了工作 . 单击 <Link> 组件将按预期工作 .

渲染组件:

<Router history={locationStore.history}>
      <div>
        <SideBar />

        <div className={mergeClass('app-content text-center', { expanded: layoutStore.sidebarOpen })}>
          <NavBar />

          <div className='page-wrapper'>
            <Route exact path='/' component={Home} key='home' />,
            <Route exact path='/stuff/:id/edit' component={StuffEdit} key='stuff.edit' />,
          </div>
        </div>
      </div>
    </Router>

位置商店:

import { observable } from 'mobx'
import createBrowserHistory from 'history/createBrowserHistory'

const history = createBrowserHistory()

class LocationStore {
  @observable history = history

  goTo (url) {
    this.history.push(url)
  }
}

export default new LocationStore()

这是我尝试改变路线的地方:

return Api.post('/stuff', formData).then((response) => {
  stuffStore.addStuff(response.data)
  locationStore.goTo(`/stuff/${response.data.stuff.id}/edit`)
})

网址在浏览器中更改,但该组件仍保留在原始页面上 . 单击生成的 Link 组件到新模型按预期工作(不刷新) .

反应版本:15.6.1
React路由器版本:4.1.2
Mobx版本:3.2.2
Mobx-react版本:4.2.2

1 回答

  • 0

    也许你可以试试这个

    <Route path="/" component={App}>
      <Route path='path0' component={UserManage}></Route>
      <Route path='path1'>
        <Route path='path11' component={component11}></Route>
        <Route path='path12' component={component12}></Route>
      </Route>
    </Route>
    
    
    in component11, you can try this way to change the route:
    
    this.props.router.push( '/path1/path12' );
    

相关问题