javascript – 为什么更高阶组件中的componentDidMount被调用多次?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 为什么更高阶组件中的componentDidMount被调用多次?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1512字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 为什么更高阶组件中的componentDidMount被调用多次?](/upload/InfoBanner/zyjiaocheng/773/3576778d81634d37af4da8a07f3bc53f.jpg)
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.这是循环
内容总结
以上是互联网集市为您收集整理的javascript – 为什么更高阶组件中的componentDidMount被调用多次?全部内容,希望文章能够帮你解决javascript – 为什么更高阶组件中的componentDidMount被调用多次?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。