React次级渲染遇到的问题 2019-09-02

一、次级渲染

什么是次级渲染?我们总是希望render返回的jsx足够小,以便于阅读理解,于是将jsx使用js function进行拆分,简化render函数,就是次级渲染。比如:

render() {
    let {renderBody} = this;
    return (
          <div className={s.dialog}>
            <Header second={second} onClose={this.clickOnClose}/>
            <div className={s.dialogBody}>
              {renderBody()}
            </div>
            <Footer resultCode={resultCode} />
          </div>
    )
  }

renderBody即为次级渲染函数,其中return了body相关的jsx,使得render函数足够简化。

二、发现问题

有时候,可能因为种种原因,需要在js function中承载部分js逻辑,但是这些js可能会为你产生一个隐藏的严重性BUG,并且这并不是一个好办法,为什么不使用function component拆分组件呢?但是,我就是这样写了。。。

这会导致什么问题?举个栗子,

function IfElse({ condition, children }) {
  const childArr = React.Children.toArray(children);
  if(condition){
    return _.get(childArr, "[0]", null);
  }

  return _.get(childArr, "[1]", null);
}

首先,封装了一个IfElse组件,用来模拟三目表达式。

然后,创建一个类组件

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: ""
    };

    this.dataModel = null;
  }

  componentDidMount(){
    setTimeout(()=>{
      this.dataModel = {getName: function (){return "西红柿"}};
      this.setState({title:'蔬菜'});
    }, 2000);
  }

  renderText = () => {
      const name = this.dataModel.getName();
      const { title } = this.state;
      return <div>{`${title}->${name}`}</div>
  };

  render() {
    let { title } = this.state;
    return (
      <div>
        <IfElse condition={title.length > 0}>
          {this.renderText()}
          <div>waiting...</div>
        </IfElse>
      </div>
    );
  }
}

使用setTimeout模拟协议请求,初始化dataModelIfElse组件根据title.length判断显示哪个子组件。这些代码,大略看一遍,很难发现问题在哪,跑起来试试

99366BBF-8608-4146-B8E9-3DADFA9B0126.png

直接报错了,getName方法找不到,因为this.dataModel为空。

为什么?明明IfElse组件开始是不会返回第一个子组件的。这是我第一时间的想法,顿时脑子出现很多浮想,this指针不对?IfElse组件有问题?还是其他什么未知问题?

经过增加各种打印,发现renderText里的打印始终会最先执行,而IfElse组件里的打印根本还没有触发,也就是说js function会优先于其他组件的逻辑执行。再次翻阅了react官网关于jsx的说明->深入 JSX,豁然开朗。

其实早就应该想明白的。

jsx只是React.createElement的语法糖,babel会将jsx转译成

React.createElement(
  'div',
  {className: 'sidebar'},
  null
)

形式的代码。

比如上面的IfElse组件,经过babel转译,则变成

React.createElement(IfElse, {
  condition: title.length > 0
}, this.renderText(), React.createElement("div", null, "waiting..."));

此时,IfElse组件还未生成,已经先执行了一次this.renderText(),所以直接报错。

三、解决办法

1、直接增加一次安全判断

renderText = () => {
    if (!this.dataModel) {
      return null;
    }
    const name = this.dataModel.getName();
    const {title} = this.state;
    return <div>{`${title}->${name}`}</div>
  };

这应该是最粗暴的方法了,哪里出问题补哪里,但是增加安全判断还是有必要的,可以有效提升软件的健壮程度。

2、不使用IfElse组件进行判断,使用js进行判断

{
   title.length > 0?this.renderText():<div>waiting...</div>
}

使用js判断,则开始的时候根本执行不到renderText方法,但是这样可读性不是很好,并且与IfElse组件的意图违背。

3、使用function component拆分组件

RenderText = () => {
    const name = this.dataModel.getName();
    const {title} = this.state;
    return <div>{`${title}->${name}`}</div>
  };

  render() {
    React.createElement(IfElse, {condition:false}, []);
    let { title } = this.state;
    let { RenderText } = this;
    return (
      <div>
        <IfElse condition={title.length > 0}>
          <RenderText />
          <div>waiting...</div>
        </IfElse>
      </div>
    );
  }

这应该是最好的解决办法了,次级渲染并不推荐使用,即使是要用,也不应包含过多逻辑处理。

这里使用了类内函数组件,复用性较差,应尽量使用独立的function component,如下所示

function VisibleText({title, name}) {
  return <div>{`${title}->${name}`}</div>;
}

render() {
    React.createElement(IfElse, {condition:false}, []);
    let { title } = this.state;
    let name = this.dataModel && this.dataModel.getName();
    return (
      <div>
        <IfElse condition={title.length > 0}>
          <VisibleText title={title} name={name} />
          <div>waiting...</div>
        </IfElse>
      </div>
    );
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原教程内容详见精益 React 学习指南,这只是我在学习过程中的一些阅读笔记,个人觉得该教程讲解深入浅出,比目前大...
    leonaxiong阅读 7,831评论 1 18
  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 12,677评论 1 33
  • 40、React 什么是React?React 是一个用于构建用户界面的框架(采用的是MVC模式):集中处理VIE...
    萌妹撒阅读 4,690评论 0 1
  • HTML模版 之后出现的React代码嵌套入模版中。 1. Hello world 这段代码将一个一级标题插入到指...
    ryanho84阅读 11,409评论 0 9
  • 3. JSX JSX是对JavaScript语言的一个扩展语法, 用于生产React“元素”,建议在描述UI的时候...
    pixels阅读 7,898评论 0 24