ReactDefaultBatchingStrategyTransaction ReactUpdatesFlushTransaction reactreconcileTransaction之间的区别

时间:2018-01-08 07:44:57

标签: reactjs

在反应中,我在源代码中看到了三个事务。我想知道它们是如何工作的。

ReactDefaultBatchingStrategyTransaction 
ReactUpdatesFlushTransaction 
ReactReconcileTransaction

在阅读之后,在我看来似乎是在一个单击事件处理程序中调用setState使用全部三个。以下是示例。

在childComp中,clickHandler会在子级上调用setState,然后调用父级handler,父级调用setState

我的问题是在上面的行动,为什么反应使用三个交易?对我来说,似乎只有一个事务就足够了(比如mysql事务)

ParentComp

class App extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            x: 1
        }
    }

    render() {
        console.log(`parent render, this.state.x=${this.state.x}`)
        return ( 
            <div>
                x in parent: {this.state.x}
                <br />
                <Child x={this.state.x} clickHandler={this.clickHandler} />
            </div>
        );
    }

    clickHandler = () => {
        this.setState({
            x: 2
        })
    }

}

ChildComp

export default class Child extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            y: 3
        }
    }

    render() {
        console.log(`child render, this.props.x=${this.props.x}, this.state.y=${this.state.y}`)
        return (
            <div>
                x in child: {this.props.x}
                <br />
                    y in child: {this.state.y}
                    <br />
                    <a href="javascript:;" onClick={this.clickHandler}>change</a>
            </div>
        );
    }

    clickHandler = () => {
        this.setState({
            y: 4
        })
        this.props.clickHandler()
    }

}

1 个答案:

答案 0 :(得分:2)

正如文档所述,setState是异步的,对状态的所有更新都是批处理并执行的,所以当你调用setState时,它会批量调用ReactDefaultBatchingStrategyTransaction的更新,现在它必须更新after setState已执行它调用ReactUpdatesFlushTransaction之后,它决定在DOM中更新所需的所有内容,从而执行ReactReconcileTransaction

所以简而言之

<强> ReactDefaultBatchingStrategyTransaction

  

context内调用提供的函数   setState和朋友分批处理组件不是   不必要地更新。

<强> ReactUpdatesFlushTransaction:

  

'ReactUpdatesFlushTransaction的包装器将清除   dirtyComponents数组并执行mount-ready入队的任何更新   处理程序(即componentDidUpdate)'

<强> ReactReconcileTransaction

  

在安装过程中使用交易,并允许保持应用程序状态安全

这些交易中的每一项都在别处独立使用,因此无法转换为单一交易

Here 是一篇很好的文章,它将引导您完成ReactJS的内部工作