GVKun编程网logo

React五——React-router(react router 5)

1

本文将分享React五——React-router的详细内容,并且还将对reactrouter5进行详尽解释,此外,我们还将为大家带来关于''react-router-redux''到''connec

本文将分享React五——React-router的详细内容,并且还将对react router 5进行详尽解释,此外,我们还将为大家带来关于''react-router-redux''到''connected-react-router''、./node_modules/react-router-dom/react-router-dom.js尝试导入错误:未从“ react-router”导出“ Navigate”、connected-react-router: react-router-dom 必须总是最后安装、javascript – React Router this.context.router.push不会重新安装组件的相关知识,希望对你有所帮助。

本文目录一览:

React五——React-router(react router 5)

React五——React-router(react router 5)

路由

npm build
cnpm i serve -g
cnpm i react-router@3.0 -S

    bogon:project macbook$ cnpm i react-router@3.0 -S
    ✔ Installed 1 packages
    ✔ Linked 23 latest versions
    ✔ Run 0 scripts
    peerDependencies WARNING react-router@3.0 requires a peer of react@^0.14.0 || ^15.0.0 but react@16.1.0 was installed
    ✔ All packages installed (24 packages installed from npm registry,used 9s,speed 27.27kB/s,json 25(70.88kB),tarball 172.32kB)
    bogon:project macbook$ 
    
npm start

构建

src下新建routes文件夹
创建routes.js文件

    import React,{ Component } from 'react'
    import { Router,Route,hashHistory } from 'react-router'
    
    import Index from '../pages/Index'
    import Position from '../pages/Position'
    import Search from '../pages/Search'
    import mine from '../pages/mine'
    
    class App extends Component {
        render() {
            return(
                <Router history = { hashHistory }>
                    <Route path="/" component={Index}>
                    <IndexRoute component={Position}></IndexRoute> //索引
                        <Route path="position" component={Position}/>
                        <Route path="search" component={Search}/>
                        <Route path="mine" component={mine}/>
                    </Route>
                </Router>
            )
        }
    }
    
    export default App

创建默认组件Index.js
src/pages/Index.js
创建子组件 进行路由跳转
import React,{ Component } from 'react'

class mine extends Component {
    render() {
        return(
            <div>mine</div>
        )
    }
}

export default mine


壳:index.js
import React,{ Component } from 'react'
import {Link} from 'react-router'

class Index extends Component {
    render() {
        return(
            <div>
                <div>
                    <Link to={{pathname: '/position',query:{name:'alice'}}}>职位</Link>
                    <Link to="/search">搜索</Link>
                    <Link to="/mine">我的</Link>
                </div>
                <div>
                    {this.props.children}
                </div>
            </div>
        )
    }
}

export default Index

高亮

<IndexLink activeStyle={{color: 'red'}} to='/'>职位</IndexLink>

传参

(1)传:
    <Link activeStyle={{color: 'red'}}  to={{pathname:"/search",query:{name:'alice'}}}>搜索</Link>
    收:
    constructor(props){
        super(props)
        console.log(this.props.location.query.name)
    }
(2)传:
    <Link activeStyle={{color: 'red'}}  to="/mine/3">我的</Link>
    收:
    constructor(props){
        super(props)
        console.log(this.props.params.id)
    }
    
   'mine/*'
   'mine(/:id)'

redirect

<Redirect from='/' to="/position"></Redirect>
<Route path="/" component={Index}>
    <Route path="position" component={Position}/>
    <Route path="search" component={Search}/>
    <Route path="mine/:id" component={mine}/>
</Route>

<IndexLink activeStyle={{color: 'red'}} to='/position'>职位</IndexLink>

路由嵌套

<Router history = { hashHistory }>
    <Redirect from='/' to="/position"></Redirect>
    <Route path="/" component={Index}>
        {/* <IndexRoute component={Position}></IndexRoute> */}
        
        <Route path="position" component={Position}>
            <Redirect from='/position/search' to="/search"></Redirect>
        </Route>
        <Route path="mine/:id" component={mine}/>
    </Route>
    <Route path="/search" component={Search}/>
    <Route path="*" component={Page404}></Route>
</Router>

/position/search的时候会重定向到/search 导航消失 可做详情页

404 免战牌页面

404.js
import React,{ Component } from 'react'

class Page404 extends Component {
    render() {
        return(
            <div>page not found</div>
        )
    }
}

export default Page404

routes.js
<Router history = { hashHistory }>
    <Route path="/" component={Index}>
        <IndexRoute component={Position}></IndexRoute>
        <Route path="position" component={Position}/>
        <Route path="search" component={Search}/>
        <Route path="mine/:id" component={mine}/>
    </Route>
    <Route path="*" component={Page404}></Route>   //放到最后
</Router>

路由守卫

<!--安装 cnpm i --save react-mixin@2-->
class App extends Component {
    handleEnter(params,replace) {
        console.log('position enter')
        console.log(params)
        replace('/mine')   //路由守卫
    }
    handleLeave(){
        console.log('position leave')
    }
    render() {
        return(
            <Router history = { hashHistory }>
                <Route path="/" component={Index}>
                    {/* <IndexRoute component={Position}></IndexRoute> */}
                    <IndexRedirect to="/position"></IndexRedirect>
                    <Route onEnter={ ({params},replace) => { this.handleEnter(params,replace) } } onLeave = { () => { this.handleLeave() } } path="position/:id" component={Position}>
                        {/* <Redirect from='/position/search' to="/search"></Redirect> */}
                        <Route path="/search" component={Search}/>
                    </Route>
                    <Route path="mine" component={mine}/>
                </Route>
                
                <Route path="*" component={Page404}></Route>
            </Router>
        )
    }
}

IndexRedirect  写到<Route/>里面
Redirect 写到外面

组件切换的时候生命周期钩子

路由守卫 onEnter onLeave 如上
unmount会被处触发 其他钩子正常

''react-router-redux''到''connected-react-router''

''react-router-redux''到''connected-react-router''

背景:
redux和react-router两者协同工作会出现,路由变化而store无法感知到,的问题。

react-router-redux :
一. 作用:
react-router-redux 是 redux 的一个中间件,加强了React Router库中history这个实例,以允许将history中接受到的变化反应到state中去。

使用方法1:

使用syncHistoryWithStore包裹browserHistory,当url改变时,会自动触发 LOCATION_CHANGE action,更改store中维护的 locationBeforeTransitions 状态对象,实现store状态的更新。

// 只需要传入react-router中的history以及redux中的store,就可以获得一个增强后的history对象。
// 将这个history对象传给react-router中的Router组件作为props,就给应用提供了观察路由变化并改变store的能力。
import { syncHistoryWithStore, routerReducer } from ''react-router-redux''
const store = createStore(
  combineReducers({
    ...reducers,
    routing: routerReducer
  })
)
const history = syncHistoryWithStore(browserHistory, store)
ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={App} />
    </Router>
  </Provider>,
  document.getElementById(‘app'')
)

// 对应的reducer.js
export const LOCATION_CHANGE = ''@@router/LOCATION_CHANGE''

const initialState = {
  locationBeforeTransitions: null
}
  1. 使用方法2:

    手动触发路由的跳转,同时需要。

    直接store.dispatch(push(''/foo'')),会触发 CALL_HISTORY_METHOD 这个action,调用中间件,等同于调用 browserHistory上相应的push方法。

// 触发路由跳转(使用redux action的方式来触发)
import { createStore, combineReducers, applyMiddleware } from ''redux'';
import { routerMiddleware, push } from ''react-router-redux''
// Apply the middleware to the store
const middleware = routerMiddleware(browserHistory)
const store = createStore(
  reducers,
  applyMiddleware(middleware)
)
// 使用dispatch手动触发 push 等操作
store.dispatch(push(''/foo''))

源码的具体实现:

// import 的 push, replace, go, goBack, goForward之类的方法出自: action.js
export const push = updateLocation(''push'')

function updateLocation(method) {
  return (...args) => ({
    type: CALL_HISTORY_METHOD,
    payload: { method, args }
  })
}

//中间件代码
export default function routerMiddleware(history) {
  return () => next => action => {
    if (action.type !== CALL_HISTORY_METHOD) {
      return next(action)
    }

    const { payload: { method, args } } = action
    history[method](...args)       //这里直接改变browserHistory
  }
}

二. react-router-redux原理图

CALL_HISTORY_METHOD,这类 action 一般会在组件内派发,它不负责 state 的修改,通过 routerMiddleware 后,会被转去调用 history。

面临的问题:
react-router-redux 只兼容 react-router 2.x and 3.x,所以要改成使用 connected-react-router 来兼容 react-router 4.x。

解决:

把之前 react-router-redux 中 store.dispatch(push(''/foo'')) 这么使用的,直接改成 history.push(''/foo'') 之类的。

参考文章:
https://blog.csdn.net/weixin_... React 的路由状态管理

./node_modules/react-router-dom/react-router-dom.js尝试导入错误:未从“ react-router”导出“ Navigate”

如何解决./node_modules/react-router-dom/react-router-dom.js尝试导入错误:未从“ react-router”导出“ Navigate”

./node_modules/react-router-dom/react-router-dom.js Attempted import error: ''Navigate'' is not exported from ''react-router''.

react-router-dom的版本是6.0.0-alpha.2,而react-router是5.2.0。 两者均已正确安装。我不确定如何解决此错误。有人可以给我任何可能的解决方法吗?

我的代码中甚至没有<Navigate to=?>行。

解决方法

为什么只安装两个都需要,这可以工作

  1. 执行npm删除react-router
  2. 删除node_modules
  3. 纱线安装或npm安装和
  4. 启动纱线或启动npm

connected-react-router: react-router-dom 必须总是最后安装

connected-react-router: react-router-dom 必须总是最后安装

如何解决connected-react-router: react-router-dom 必须总是最后安装

我从我的开发文件夹中排除了我的 node_modules 文件夹,并且只有一个指向它的软链接(因此它不会同步到云)。我使用 connected-react-router 并且一切正常,直到我之后安装任何其他 npm 包。然后我在浏览器中收到错误:Uncaught Error: Invariant Failed: You should not use <Switch> outside a <Router> 当我再做 npm install react-router-dom 时,一切都会恢复正常。出于某种原因,react-router-dom 必须始终是最新安装的软件包。

即使我直接包含 node_modules 文件夹,而不是作为软链接,也会出现此问题。有没有人知道这是怎么发生的以及如何解决这个问题?

javascript – React Router this.context.router.push不会重新安装组件

javascript – React Router this.context.router.push不会重新安装组件

我们有一个click处理程序,它使用react router 2.0 this.context.router.push()更新url.见下文:

selectRelatedJob(slug) {
  JobActionCreators.fetchJobPage(slug);
  JobsActionCreators.getRelatedJobs({'sl': slug});
  this.context.router.push({pathname: '/job',query: {sl: slug}});
}

我们的目标是基于“sl”查询字符串获取新数据,但我们的componentwillMount()方法没有被调用,因为我们正在将url更新为相同的路径—只是一个不同的查询字符串.而是调用更新生命周期方法.我们当前的方法是调用操作创建器直接在单击处理程序中获取数据.但是,这似乎是多余的和hacky,因为我们已经更新了url.理想情况下,组件将被卸载并重新安装.

以下是嵌套路线:

<Route component={App}>
  <Route path="/" component={HomePage}/>
    <Route path="job" component={JobPage}/>
    <Route path="job/" component={JobPage}/>
  </Route>
</Route>

使用不同的查询字符串导航到当前URL的最佳案例实践是什么?

解决方法

传入不同的组件.

<Route path="job/:id" component={JobDetailPage} />

今天关于React五——React-routerreact router 5的分享就到这里,希望大家有所收获,若想了解更多关于''react-router-redux''到''connected-react-router''、./node_modules/react-router-dom/react-router-dom.js尝试导入错误:未从“ react-router”导出“ Navigate”、connected-react-router: react-router-dom 必须总是最后安装、javascript – React Router this.context.router.push不会重新安装组件等相关知识,可以在本站进行查询。

本文标签: