关于这里有没有你想要的react-router和reactrouter官网的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于''react-router-redux''到''connecte
关于这里有没有你想要的react-router和react router 官网的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于''react-router-redux''到''connected-react-router''、./node_modules/react-router-dom/react-router-dom.js尝试导入错误:未从“ react-router”导出“ Navigate”、Angular 2 router.navigate - Angular 2 router.navigate、angular-ui-router – Angular UI Router – 允许任何查询字符串参数等相关知识的信息别忘了在本站进行查找喔。
本文目录一览:- 这里有没有你想要的react-router(react router 官网)
- ''react-router-redux''到''connected-react-router''
- ./node_modules/react-router-dom/react-router-dom.js尝试导入错误:未从“ react-router”导出“ Navigate”
- Angular 2 router.navigate - Angular 2 router.navigate
- angular-ui-router – Angular UI Router – 允许任何查询字符串参数
这里有没有你想要的react-router(react router 官网)
由于React Router 4.0已经正式发布,所以该博文分React Router 和 React Router 4.0 进行分类讨论!该博文会持续更新中,欢迎大家一起讨论与补充!
我相信用过react一般都用过react-router,那就很有必要说说用react-router实现的一些常用功能了,比如组件按需加载、用户登录验证、刷新当前路由。。。在这篇文章中,我将列出一些react-router使用小技巧,希望每个读者都能至少从中学到一个有用的技巧!
一、按需加载
React Router:使用 getComponent + require.ensure
实现按需加载
getComponent
相比以前的 component
属性,这个方法是异步的,也就是当路由匹配时,才会调用这个方法。
require.ensure(dependencies,callback,chunkName)
而 require.ensure
是 webpack 提供的方法,这也是按需加载的核心方法。第一个参数是依赖的模块数组,第二个是回调函数,该函数调用时会传一个require参数,第三个是模块名,用于构建时生成文件时命名使用
实现按需加载核心代码如下:
import React,{ Component } from 'react'; // react核心 import { Router,Route,Redirect,IndexRoute,browserHistory } from 'react-router'; /** * (路由根目录组件,显示当前符合条件的组件) * * @class Roots * @extends {Component} */ class Roots extends Component { render() { return ( <div>{this.props.children}</div> ); } } const history = browserHistory; // 首页 const home = (location,cb) => { require.ensure([],require => { cb(null,require('./Home').default); },'home'); } const RouteConfig = ( <Router history={history}> <Route path="/" component={Roots}> <IndexRoute getComponent={home} /> <Route path="/home" getComponent={home} /> <Route path="/login" component={login} /> <Redirect from="*" to="/home" /> </Route> </Router> ); export default RouteConfig;
React Router 4.0:使用 babel-plugin-Syntax-dynamic-import + react-loadable
实现按需加载
首先确保已安装 babel-plugin-Syntax-dynamic-import
和 react-loadable
,未安装请先安装:
npm i -D babel-plugin-Syntax-dynamic-import npm i -S react-loadable
实现按需加载核心代码如下:
import React,{ Component } from 'react'; import { browserRouter,HashRouter,Switch,Redirect} from 'react-router-dom'; import createbrowserHistory from 'history/createbrowserHistory' const history = createbrowserHistory(); // 按路由拆分代码 import Loadable from 'react-loadable'; const loadingComponent = ({ isLoading,error }) => { // Handle the loading state if (isLoading) { return <div>Loading...</div>; } // Handle the error state else if (error) { return <div>Sorry,there was a problem loading the page.</div>; } else { return null; } }; const Index = Loadable({ loader: () => import('./Index'),loading: loadingComponent }); const Home= Loadable({ loader: () => import('./Home'),loading: loadingComponent }); const Login= Loadable({ loader: () => import('./Login'),loading: loadingComponent }); /** * (路由根目录组件,显示当前符合条件的组件) * * @class Roots * @extends {Component} */ class Roots extends Component { render() { return ( <div>{this.props.children}</div> ); } } let Router = process.env.NODE_ENV !== 'production' ? browserRouter : HashRouter; const RouteConfig = ( <Router history={history}> <Switch> <Route path="/" exact component={Index} /> <Route path="/home" component={Home} /> <Route path="/login" component={Login} /> <Redirect from='' to="/" /> </Switch> </Router> ); export default RouteConfig;
二、实现登录验证
React Router:利用 Route 的 onEnter 钩子在渲染对象组件前做拦截操作实现登录验证;
import React,'home'); } // 登录验证 const requireAuth = (nextState,replace) => { if(true) { // 未登录 replace({ pathname: '/login',state: { nextPathname: nextState.location.pathname } }); } } const RouteConfig = ( <Router history={history}> <Route path="/" component={Roots}> <IndexRoute getComponent={home} onEnter={requireAuth} /> <Route path="/home" getComponent={home} onEnter={requireAuth} /> <Route path="/login" component={login} /> <Redirect from="*" to="/home" /> </Route> </Router> ); export default RouteConfig;
React Router4.0:在 Route 的 render 属性上添加一个函数实现登录验证;
实现登录验证核心代码如下:
import React,loading: loadingComponent }); /** * (路由根目录组件,显示当前符合条件的组件) * * @class Roots * @extends {Component} */ class Roots extends Component { render() { return ( <div>{this.props.children}</div> ); } } // 登录验证 function requireAuth(Layout,props) { if (true) { // 未登录 return <Redirect to="/login" />; } else { return <Layout {...props} /> } } let Router = process.env.NODE_ENV !== 'production' ? browserRouter : HashRouter; const RouteConfig = ( <Router history={history}> <Switch> <Route path="/" exact component={Index} /> <Route path="/home" component={props => requireAuth(Home,props)} /> <Route path="/login" component={Login} /> <Redirect from='' to="/" /> </Switch> </Router> ); export default RouteConfig;
三、实现点击左侧菜单刷新当前组件
React Router:利用 Route 的 createElement 钩子实现点击左侧菜单刷新当前组件;
实现点击左侧菜单刷新当前组件核心代码如下:
import React,'home'); } // 此处为要点击刷新的组件 const arr = [ home ]; // 开关优化 let onOff =false; // 页面强制刷新,如果需要强制刷新在路由中添加onChange事件以及在组件数组添加 const createElement=(component,props) =>{ if (props.children && onOff || props.children && arr.includes(props.routes.slice(-1)[0].getComponent)) { let children = Object.assign({},props.children,{key : `${window.location.pathname}` + new Date().getTime()}) props = { ...props,children }; onOff = false; } return React.createElement(component,props) } const onChange = (props,next) => { onOff = true console.log(`${next.location.pathname}`,'change'); } const RouteConfig = ( <Router history={history} createElement = {createElement}> <Route path="/" component={Roots}> <IndexRoute getComponent={home} /> <Route path="/home" getComponent={home} /> <Route path="/login" component={login} /> <Redirect from="*" to="/home" /> </Route> </Router> ); export default RouteConfig;
欢迎大家一起讨论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
}
使用方法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=?>
行。
解决方法
为什么只安装两个都需要,这可以工作
- 执行npm删除react-router
- 删除node_modules
- 纱线安装或npm安装和
- 启动纱线或启动npm
Angular 2 router.navigate - Angular 2 router.navigate
问题:
I''m trying to navigate to a route in Angular 2 with a mix of route and query parameters. 我正在尝试使用路由和查询参数的组合导航到 Angular 2 中的路由。
Here is an example route where the route is the last part of the path: 这是一个示例路线,其中路线是路径的最后一部分:
{ path: '':foo/:bar/:baz/page'', component: AComponent }
Attempting to link using the array like so: 尝试使用数组进行链接,如下所示:
this.router.navigate([''foo-content'', ''bar-contents'', ''baz-content'', ''page''], this.params.queryParams)
I''m not getting any errors and from what I can understand this should work. 我没有收到任何错误,据我所知,这应该可行。
The Angular 2 docs (at the moment) have the following as an example: Angular 2 文档(目前)具有以下示例:
{ path: ''hero/:id'', component: HeroDetailComponent }
[''/hero'', hero.id] // { 15 }
Can anyone see where I''m going wrong? 谁能看到我哪里出错了? I''m on router 3. 我在路由器 3 上。
解决方案:
参考: https://stackoom.com/en/question/2Zzgrangular-ui-router – Angular UI Router – 允许任何查询字符串参数
通常使用UI路由器,您可以定义类似这样的路由:
$stateProvider.state('test',{ url: '/test?testQueryStringParam',templateUrl: 'Test.html',controller: 'TestController' });
然后在我的控制器中,我可以使用$stateParams访问testQueryStringParam.
但是,使用UI路由器,您无法访问路径定义中未指定的任何查询字符串参数.
Angular框架附带的路由器确实允许您这样做.所以我尝试使用我的UI路由器定义的$location服务.这确实很有效.
当我想添加查询字符串参数时,我使用:
$location.search("paramName","paramValue");
当我想获取查询字符串值时,我只是使用:
$location.search()
这会更新URL,但不会重新实例化控制器(如$state.go($state.current,{},{reload:true})).这似乎不是一个大问题,因为我可以自己重新加载数据.但是,如果您在浏览器中使用后退按钮,它将再次更改URL,但不会重新实例化控制器.
无论如何还有
>我可以使用UI路由器来实现这一点吗?
>获取使用$location实际重新实例化控制器的解决方法.
作为最后的手段,我也尝试指导更新window.location,但这会刷新整个页面,这是不可接受的.
谢谢
$stateProvider.state('test',{ url: '/test?testQueryStringParam',params: { optParam: null,},controller: 'TestController' });
如您所见,optParam是一个可选参数,其默认值为null,在URL中不可见
您可以使用$stateParams在控制器中访问此参数
$stateParams.optParam
这是一个有用的blog
关于这里有没有你想要的react-router和react router 官网的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于''react-router-redux''到''connected-react-router''、./node_modules/react-router-dom/react-router-dom.js尝试导入错误:未从“ react-router”导出“ Navigate”、Angular 2 router.navigate - Angular 2 router.navigate、angular-ui-router – Angular UI Router – 允许任何查询字符串参数等相关内容,可以在本站寻找。
本文标签: