• 正式学习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
  • 相关阅读:
    推荐一个不错的在线Linux学习平台(免安装系统)
    C#基本语法知识
    GDI+ 使用LockBits和指针加快处理速度
    C#对图像像素处理的三种方式
    [转]video4linux(v4l)使用摄像头的实例基础教程与体会
    Eclipse Qt开发环境的建立
    c#图像处理基础
    [转]超酷的图像效果
    Qt开发环境的建立
    C++模版全掌握(实例)
  • 原文地址:https://www.cnblogs.com/huenchao/p/6141076.html
Copyright © 2020-2023  润新知