ckinmind / react-cnode

👨🏻‍💻React构建的cnode社区(附详细问题说明)
https://ckinmind.github.io/react-cnode
15 stars 7 forks source link

关于路由跳转(在组件和异步action中) #5

Open ckinmind opened 7 years ago

ckinmind commented 7 years ago

问题:

  1. 如何实现路由跳转
ckinmind commented 7 years ago

参考资料:阮一峰:React Router 使用教程

  1. 第一种方法是使用browserHistory.push
  2. 第二种方法是使用context对象

第一种方法是使用browserHistory.push

import { browserHistory } from 'react-router'

// ...
  handleSubmit(event) {
    event.preventDefault()
    const userName = event.target.elements[0].value
    const repo = event.target.elements[1].value
    const path = `/repos/${userName}/${repo}`
    browserHistory.push(path)
  },

第二种方法是使用context对象

export default React.createClass({

  // ask for `router` from context
  contextTypes: {
    router: React.PropTypes.object
  },

  handleSubmit(event) {
    // ...
    this.context.router.push(path)
  },
})
ckinmind commented 7 years ago

参考资料:react-router 用JS控制跳转

import { History } from 'react-router'; 其实如果你调用History的Component是直接被react-router管理的话,你不需要mixin History。直接在this.props就有,这是自动加进来的。

this.props.history.pushState(null, '/foo')}
ckinmind commented 7 years ago

使用hashHistory做路由跳转

import {  hashHistory } from 'react-router';
 hashHistory.push({
                  pathname: '/signin',
              });

使用browserHistory也一样

import {  browserHistory} from 'react-router';
 browserHistory.push({
                  pathname: '/signin',
              });

在actions也可以这么操作,这样就可以在异步action做跳转

参考资料:react-router 中的history 参考资料:react-router API 接口