Skip to content

请教关于setState的两个问题 #1

@msforest

Description

@msforest

你好,看完这篇文章,我有两个问题请教一下,还请解答:

  1. setState的异步问题
***
onClick(){
  this.setState(partialState);
  this.setState(partialState);
}
***

每次调用setState时,会调用父类的setState,此时会进入ReactUpdateQueue中,然后会把partialState存放到ReactCompositeComponent实例对象的一个队列中,经过一系列步骤,_processPendingState该方法会对partialState,然后进入到render中。

在这一系列调用过程中,我没有看到哪一步会停止对第一个setState退出当前调用栈,肯定就不会去执行第二个setState,即_processPendingState该方法处理的队列中只有一个partialState,那就谈不上Object.assign会把第二个覆盖第一个state。因为js是单线程,而且底层没有发起异步操作。所以有点疑问

  1. setState里面的updater
function ReactComponent(props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

updater是由ReactCompositeComponent调用new Component时传入的第三个参数

var inst = new Component(publicProps, publicContext, updateQueue);

然后像我们一般定义组件是这样的

class Test extends React.Component{
  constructor(props){
    super(props); // 没有传入第二三个参数
  }
}

写这样的代码,并没有传入第三个参数,为何updater还能用的这么好?

thanks in advance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions