的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在高阶组件中多次调用?
connect()(wrap(Wrapper)); < - 用包裹替换 –
@ffxsam对不起如果我不正确地理解你的评论,我的英语不太好。但是,如果我没有错,那么当这些组件('Wrapper'和'Wrapped')已经挂载时,只要未卸载componentDidMount,它将不会被再次调用。我的意思是这两个'componentDidMount'总是被调用,只要道具改变了。 –
哦,对不起!我错过了关于导致'componentDidMount'再次触发的道具变化的部分。很奇怪。 – ffxsam