const MyApi = {
count: 0,
subscribe(cb) {
this.intervalId = setInterval(() => {
this.count++
cb(this.count)
}, 1000)
},
unSubscribe() {
clearInterval(this.intervalId)
this.reset()
},
reset() {
this.count = 0
}
}
componentWillUnmount() {
MyApi.unSubscribe()
}
/**
*
* @param {*} nextProps
* @param {*} nextState
* 关于渲染问题
*/
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.num === this.props.num) {
return false
}
return true
}
/// 第二种方式
/**
* purecomponent 会自动对数据进行浅比较, 数据简单 不会刷新
*/
class Child extends React.PureComponent{
render() {
return (
<div>
child1111111111111
</div>
)
}
}
export default Child
import React, {Fragment} from 'react';
<Fragment>
</Fragment>
或者
<>
</>
import React from 'react';
import PropTypes from 'prop-types'
const A = (props) => {
return (
<div>
<B />
</div>
)
}
/**
*
* 路由 this.props.history('/'); 必须是路有直接子元素, 如果是孙子元素,则不能用
*
* withRouter
*
*/
const B = (props, context) => {
return (
<div>
{context.color}
</div>
)
}
export default class Demo3 extends React.Component {
getChildContext() {
return {
color: 'red'
}
}
render() {
return (
<div>
<A />
</div>
)
}
}
B.contextTypes= {
color: PropTypes.string
}
Demo3.childContextTypes = {
color: PropTypes.string
}