的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