2016-06-28 106 views
2

docs说:为什么高级组件中的componentDidMount不止一次调用?

初步呈现发生后调用一次,只有客户端(而不是服务器上),请立即 。

现在,当我尝试创建一个高阶组件:

import React from 'react'; 
import { connect } from 'react-redux'; 

function wrap(Wrapped) { 

    class Wrapper extends React.Component { 
    componentDidMount() { 
     // I will place some reusable functionality here which need to 
     // be called once on mounted. 
     console.log('wrapper component mounted'); 
    } 
    render() { 
     return <Wrapped {...this.props}/> 
    } 
    } 
    return Wrapper; 
} 

class Wrapped extends React.Component { 
    componentDidMount() { 
    console.log('wrapped component mounted'); 
    } 
    render() { 
    return <div></div>; 
    } 
} 

connect()(wrap(Wrapped)); 

现在,每次出现在道具的任何变化时,控制台将打印:

'wrapped component mounted' 
'wrapper component mounted' 

如果我删除Wrapper,它只会打印一次(当第一次安装 时):

`wrapped component mounted` 

那么,为什么componentDidMount在高阶组件中多次调用?

+0

connect()(wrap(Wrapper)); < - 用包裹替换 –

+0

@ffxsam对不起如果我不正确地理解你的评论,我的英语不太好。但是,如果我没有错,那么当这些组件('Wrapper'和'Wrapped')已经挂载时,只要未卸载componentDidMount,它将不会被再次调用。我的意思是这两个'componentDidMount'总是被调用,只要道具改变了。 –

+0

哦,对不起!我错过了关于导致'componentDidMount'再次触发的道具变化的部分。很奇怪。 – ffxsam

回答

1

connect()(wrap(Wrapper)); < - 替换为包装

我已经测试过它。它的工作原理。

function wrap(Wrapped) { 
    class Wrapper extends React.Component { 
    componentDidMount() { 
     console.log('wrapper component mounted'); 
    } 
    render() { 
     return <Wrapped {...this.props}/> 
    } 
    componentDidUpdate(prevProps, prevState){ 
     console.log(this.props); 
    } 
    } 
    return Wrapper; 
} 
class Wrapped extends React.Component { 
    componentDidMount() { 
    console.log('wrapped component mounted'); 
    } 
    componentDidUpdate(prevProps, prevState){ 
     console.log(this.props); 
    } 
    render() { 
    return <div></div>; 
    } 
} 

connect(state=>({state}))(wrap(Wrapped)); 

包装FUNC返回包装,你无法通过包装成包FUNC。它的循环

+0

对不起,我错过了输入问题时打字。我更新了问题 –

+0

,但它只调用一次componentDidMount –

+0

你确定吗?你是如何测试的?它在我的情况下每次都被调用。 –

相关问题