docs说:
Invoked once, only on the client (not on the server), immediately
after the initial rendering occurs.
现在,当我尝试创建更高阶的组件时:
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));
现在,每次在props中发生任何更改时,控制台都会打印出:
'wrapped component mounted'
'wrapper component mounted'
如果我删除Wrapper,它只打印一次(安装时)
在第一时间):
`wrapped component mounted`
那么,为什么componentDidMount在更高阶的组件中不止一次被调用?
最佳答案 连接()(包裹物(包装)); < – 用Wrapped替换 我测试了它.它有效.
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));
wrap func返回Wrapper,你无法将Wrapper传递给wrap func.这是循环