正式学习React (七) react-router 源码分析

学习react已经有10来天了,对于react redux react-redux 的使用流程和原理,也已经有一定的了解,在我上一篇的实战项目里,我用到了react-route,其实对它还只是

停留在看完阮神的博客的基础上,一丢丢的小认识,对history 到底怎么用,Route里的我见别人还写了getcomponent代替component也不是很清楚。决定好好分析一下

react-route。咱们一个一个组件来学习。

 

PS: 十几天的学习,我发现我的学习方式错了,其实应该直接先用一遍再来看源码,结果我反过来了,为了修改我的学习方式,我先停2天,等我用完再来写。。

 

我们先来看下Router是个什么组件:

1  getDefaultProps() {
2     return {
3       render(props) {
4         return <RouterContext {...props} />
5       }
6     }
7   },
View Code

 

1:首先在Router里面先会生成一个RouterContext的js对象。作为newTree.

1 const RouterContext = React.createClass({
2 
3   mixins: [ ContextProvider('router') ],
4 
5              .....
6   },
View Code

 

2:在RouterContext里会执行minixs,添加的是ContextProvider返回的方法。

 1 const contextProviderShape = PropTypes.shape({
 2   subscribe: PropTypes.func.isRequired,
 3   eventIndex: PropTypes.number.isRequired
 4 })
 5 
 6 function makeContextName(name) {
 7   return `@@contextSubscriber/${name}`
 8 }
 9 
10 export function ContextProvider(name) {
11   const contextName = makeContextName(name)
12   const listenersKey = `${contextName}/listeners`
13   const eventIndexKey = `${contextName}/eventIndex`
14   const subscribeKey = `${contextName}/subscribe`
15 
16   return {
17     childContextTypes: {
18       [contextName]: contextProviderShape.isRequired
19     },
20 
21     getChildContext() {
22       return {
23         [contextName]: {
24           eventIndex: this[eventIndexKey],
25           subscribe: this[subscribeKey]
26         }
27       }
28     },
29 
30     componentWillMount() {
31       this[listenersKey] = []
32       this[eventIndexKey] = 0
33     },
34 
35     componentWillReceiveProps() {
36       this[eventIndexKey]++
37     },
38 
39     componentDidUpdate() {
40       this[listenersKey].forEach(listener =>
41         listener(this[eventIndexKey])
42       )
43     },
44 
45     [subscribeKey](listener) {
46       // No need to immediately call listener here.
47       this[listenersKey].push(listener)
48 
49       return () => {
50         this[listenersKey] = this[listenersKey].filter(item =>
51           item !== listener
52         )
53       }
54     }
55   }
56 }
View Code

 

转载于:https://www.cnblogs.com/huenchao/p/6141076.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值