生命周期中有 forceUpdate 。
我们像这样使用它:
import { lifecycle } from 'recompose';
const listensForChangingModel = ( propName='model' ) => lifecycle( {
componentDidMount() {
this.onModelChanged = () => this.forceUpdate();
this.props[ propName ].on( 'change', this.onModelChanged );
},
componentWillUnmount() {
this.props[ propName ].off( 'change', this.onModelChanged );
},
componentDidUpdate( prevProps ) {
if ( prevProps[ propName ].cid !== this.props[ propName ].cid ) {
prevProps[ propName ].off( 'change', this.onModelChanged );
this.props[ propName ].on( 'change', this.onModelChanged );
}
},
} );
export default listensForChangingModel;
这会产生一个高阶组件,当模型触发更改事件时强制更新。