• 定时器, 订阅的事件 离开页面移除
    1. const MyApi = {
    2. count: 0,
    3. subscribe(cb) {
    4. this.intervalId = setInterval(() => {
    5. this.count++
    6. cb(this.count)
    7. }, 1000)
    8. },
    9. unSubscribe() {
    10. clearInterval(this.intervalId)
    11. this.reset()
    12. },
    13. reset() {
    14. this.count = 0
    15. }
    16. }
    17. componentWillUnmount() {
    18. MyApi.unSubscribe()
    19. }
    • 父组件刷新 子组件是否需要刷新
    1. /**
    2. *
    3. * @param {*} nextProps
    4. * @param {*} nextState
    5. * 关于渲染问题
    6. */
    7. shouldComponentUpdate(nextProps, nextState) {
    8. if (nextProps.num === this.props.num) {
    9. return false
    10. }
    11. return true
    12. }
    13. /// 第二种方式
    14. /**
    15. * purecomponent 会自动对数据进行浅比较, 数据简单 不会刷新
    16. */
    17. class Child extends React.PureComponent{
    18. render() {
    19. return (
    20. <div>
    21. child1111111111111
    22. </div>
    23. )
    24. }
    25. }
    26. export default Child
    • 嵌套根元素 使用Fragment
    1. import React, {Fragment} from 'react';
    2. <Fragment>
    3. </Fragment>
    4. 或者
    5. <>
    6. </>
    • 多代传参,用 context 上下文
    1. import React from 'react';
    2. import PropTypes from 'prop-types'
    3. const A = (props) => {
    4. return (
    5. <div>
    6. <B />
    7. </div>
    8. )
    9. }
    10. /**
    11. *
    12. * 路由 this.props.history('/'); 必须是路有直接子元素, 如果是孙子元素,则不能用
    13. *
    14. * withRouter
    15. *
    16. */
    17. const B = (props, context) => {
    18. return (
    19. <div>
    20. {context.color}
    21. </div>
    22. )
    23. }
    24. export default class Demo3 extends React.Component {
    25. getChildContext() {
    26. return {
    27. color: 'red'
    28. }
    29. }
    30. render() {
    31. return (
    32. <div>
    33. <A />
    34. </div>
    35. )
    36. }
    37. }
    38. B.contextTypes= {
    39. color: PropTypes.string
    40. }
    41. Demo3.childContextTypes = {
    42. color: PropTypes.string
    43. }