边黎安 reactnataive 0.60 react 最深最全的react 的原理探究 死磕源码

1 redvx 的中间件的原理是什么?

改装dispactch  派发action -》(中间件(redvx-thunk (转化成fun))(store.dispatch)) store =》reducer 


redvx-thunk(源码)

redux-thunk的源码非常简洁,出去空格一共只有11行,这11行中如果不算上},则只有8行。最后三行模块的导出方法很好理解,

// thunk的内容如下
({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }
    return next(action);
  }

// thunk.withExtraArgument的结果如下
function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }
    return next(action);
  };
}
thunk.withExtraArgument允许给返回的函数传入额外的参数,它比较难理解的部分和thunk一样,如下:

({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }
    return next(action);
  }
看来,要解开dispatch,getState,next,action从哪里来,我们还需要再看看applyMiddleware的源码,如下:

export default function applyMiddleware(...middlewares) {
  return (createStore) => (...args) => {
    const store = createStore(...args)
    let dispatch = store.dispatch
    let chain = []

    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}
上述代码使用函数参数的解构加上连用三个箭头函数,显得非常简洁,单同时也带来了理解的困难(这也是箭头函数的缺点之一)。把上述代码在babel REPL中转译为ES5语法后

我们先看看,在reudx中我们如何使用中间件: 

可以看出其中middleware执行时传入的参数对象middlewareAPI中确实包含getState和dispatch两项,next则来自dispatch = compose(...chain)(store.dispatch)这一句中的store.dispatch,而action在dispatch某个action时传入。

let store = createStore(
    reducer,
    applyMiddleware(thunk)
);
"use strict";

function createThunkMiddleware(extraArgument) {
  return function (_ref) {
    var dispatch = _ref.dispatch,
        getState = _ref.getState;
    return function (next) {
      return function (action) {
        if (typeof action === "function") {
          return action(dispatch, getState, extraArgument);
        }
        return next();
      };
    };
  };
}
2 react 性能 优化 

immuatable.js

class test extends React.PureComponent {

constructor(props){

super(props)

}

render(){

}

}

插入一个 : 

3. 虚拟dom是什么? key 值 相同 就可以复用   diff算法 是 枉深层次遍历  n平方 降低到n  

4. webpack  vue 是借助了 loader 完成 jsx 代码的转化    react 是 使用babel - preset-react

5  setstate 一般怎么用 是一个 调和的过程 

this.setState(()=>({ name: 'dell'

}))

返回一个函数的好处  不会接越是

<input refs="input" value={this.state.age}>

改写一下 setstate 的 写法  this.setState((preState)=>{

age: ++ prevState.age})

this.refs.input.value 

5.什么时候使用refs 你在什么场景下需要操作dom

 渲染一个图片 获取这个图片的宽高

class test entends component {

super(rpops);

componentdidmount (){

window.addEventlistenre('scroll',(()=>{this.setState({

top: document.body.scrollTop})}))}

componentUn

render() {

return(){

return<div  ref=(div)={

this.div = div

}></di}}

}

6 .高阶组件的用的多不多
import React from 'react';
export const ThemeContext = React.createContext({
    theme: '#ffffff',
    toggleTheme: () => {},
   });


<ThemeContext.Provider 
 value ={{
    theme:"dark" ,
    toggleTheme:()=>{
        console.warn('bianbianhaoshuai');
    }
}}
>
    <AGLeftTip
        title={this.state.deadline? `有效期: ${this.state.deadline} 00:00 - ${this.state.deadline} 23:59`:''}

    />


</ThemeContext.Provider>

                

7 受控组件 和 非受控组件 

8 函数组件 和hooks 

9 this 指向  bind 放在 constructor 里面  事引用只有一份

10 react。memo(function test)

11 哪个生命周期发送 ajax
 compoenntdidmount 里面 追根溯源 
 ssr 的地方 将被 服务端渲染占用
12 ssr 的原理
  虚拟dom 好处 让我们的代码运行速度更快 react代码 变成了一个对象 让他可以在服务端执行 nodejs 运行起来
  借助虚拟dom 

13 redvx-sage  的设计思想是什么
  side- effects   扩充

14 react vue jquery 能否在 项目中 共存。关键看怎么共存 

ReactDom.render(<App>,document.getElmentbyId('react'))
15 组件是什么 类是什么 类被编译成什么 ?
模块的概念 被提出来 存在于 webpack 的打包工具里面
import a from './a.js'
import 'style.css'

组件指 的是页面的一部分。
类 就是一个构造函数
函数是功能集合 

16 如何跟着社区成长
怎么了解 新的react 的新知识点
关注twitter 的文章  领先掘金 知乎 等等 

17 避免ajax 页面的重复渲染问题 
redvx 一起管理 
18 react-router4 的核心思想 
4.0   路由也变成了 一个组件, 他将会 非常的灵活   都是<link><link> 
<route></route>
变成了 一个个 小的组件

19 reselect 这个库  他就是派生数据 
20 react-router 的基本原理 hashhistory browerhistrory
apaqi 或者  nigx 的配置 才可以使用 browerhistory  需要后台服务器重镜像了
21 什么情况下使用异步组件 
reloadable 这个库 路由懒加载 react 里面怎么用  其实就是es6 试验阶段
import(./home).then
require.ensure 

222 react 框架已经帮我们做好了 xss的防范
dangerrouslysetinnerhtml ={{ __htnml: '<script>'}}

23 getdervedstatefromprops

24 immuatable 的时间 
页面毫无变化
原因:b每次都指向了同一个引用对象obj,引用地址没变,shouldComponentUpdate只会做浅比较,自然会返回false,页面不会重新渲染

到这里应该能很好的解释了shouldComponentUpdate的特点

那么如何处理引用对象的情况呢?目前最推崇的做法是使用不可变对象immutablejs,facebook自家出的
GitHub - facebook/immutable-js
好了,研究去吧

另外,还有个pureComponent,看下官方介绍就好了
React Top-Level API - React

React.PureComponent
React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

Note

React.PureComponent’s shouldComponentUpdate() only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only extend PureComponent when you expect to have simple props and state, or use forceUpdate() when you know deep data structures have changed. Or, consider using immutable objects to facilitate fast comparisons of nested data.

Furthermore, React.PureComponent’s shouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.

说到底,也只是会自动使用shouldComponentUpdate钩子的普通Component而已,没什么特殊的
image

二、组件响应速度(InteractionManager、requestAnimationFrame、setNativeProps)
1)InteractionManager
InteractionManager和requestAnimationFrame(fn)的作用类似,都是为了避免动画卡顿,具体的原因是边渲染边执行动画,或者有大量的code计算阻塞页面进程。
InteractionManager.runAfterInteractions是在动画或者操作结束后执行

InteractionManager.runAfterInteractions(() => {
  // ...long-running synchronous task...
});
2)requestAnimationFrame
window.requestAnimationFrame - Web API 接口 | MDN
使用requestAnimationFrame(fn)在下一帧就立即执行回调,这样就可以异步来提高组件的响应速度;

OnPress() {
  this.requestAnimationFrame(() => {
    // ...setState操作
  });
}
还有setImmediate/setTimeout(): 这个是比较原始的奔方法,很有可能影响动画的流畅度

3) setNativeProps
Direct Manipulation · React Native
通过Direct Manipulation的方式直接在底层更新了Native组件的属性,从而避免渲染组件结构和同步太多视图变化所带来的大量开销。

这样的确会带来一定的性能提升,同时也会使代码逻辑难以理清,而且并没有解决从JS侧到Native侧的数据同步开销问题。

因此这个方式官方都不再推荐,更推荐的做法是合理使用setState()和shouldComponentUpdate()方法解决这类问题


  shouldComponentUpdate(nextProps, nextState) {
        const thisProps = this.props || {};
        const thisState = this.state || {};
        nextState = nextState || {};
        nextProps = nextProps || {};
        if (Object.keys(thisProps).length !== Object.keys(nextProps).length ||
            Object.keys(thisState).length !== Object.keys(nextState).length) {
            return true;
        }
        for (const key in nextProps) {
            if (!is(thisProps[key], nextProps[key])) {
                return true;
            }
        }
        for (const key in nextState) {
            if (!is(thisState[key], nextState[key])) {
                return true;
            }
        }
        return false;
    }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值