美文网首页JavaScript 进阶营
一分钟带你重识React 中 componentWillRece

一分钟带你重识React 中 componentWillRece

作者: sherlockAndy | 来源:发表于2019-08-18 18:25 被阅读1次

问题: 关于React 中的 的钩子函数 componentWillReceiveProps() 会在什么情况下触发???
大众的回答: 当props发生变化时会触发!
那么 , 一定是当 props 发生变化时 , 该方法才会执行吗 ? 或者说: 如果props 没有发生变化 , 那么该方法就不会执行?

跑一下代码看看吧 !

import * as React from "react";
import className from "./style/index.less";

interface IsState {
privateData: number[];
subData: number[];
}
class App extends React.Component<{}, IsState> {
readonly state: IsState = {
  privateData: [1, 2, 3],
  subData: [3, 2, 1]
};
/**
 * 修改子组件数据
 */
handleSubDataChange = () => {
  this.setState(
    {
      subData: [...this.state.subData, 0]
    },
    () => {
      console.log("handleSubDataChange", this.state.subData);
    }
  );
};
/**
 * 修改父组件数据
 */
handlePrivateDataChange = () => {
  this.setState(
    {
      privateData: [...this.state.privateData, 1]
    },
    () => {
      console.log("handlePrivateDataChange", this.state.privateData);
    }
  );
};

render() {
  console.log(1);
  return (
    <div className={className.wrap}>
      <div>父组件:{this.state.privateData}</div>
      <SubComponent data={this.state.subData} />
      <button onClick={this.handleSubDataChange}>修改子组件数据</button>
      <button onClick={() => this.handlePrivateDataChange()}>
        修改父组件数据
      </button>
    </div>
  );
}
}
interface PropsType {
data: number[];
}

class SubComponent extends React.Component<PropsType> {
constructor(props: any) {
  super(props);
}
componentWillReceiveProps(nextProps: PropsType) {
  console.log(nextProps, "componentWillReceiveProps");
}
render() {
  return <div>子组件:{this.props.data}</div>;
}
}
export default App;

我们会发现无论是修改了父组件的数据, 还是修改了子组件的数据, 这个方法都会被触发 , 也就是说 , 并非只有子组件 props 发生变化时该方法才会被调用的 , 按照逻辑推理的说法 , props发生了变化 , 一定会引起子组件的componentWillReceiveProps()触发 , 但反过来 , 子组件的componentWillReceiveProps( ) 触发 , 并不能证明 props 发生了变化. 即 A=>B != B=>A , 即A是B的充分不必要条件, skr , skr ~~

相关文章

  • 一分钟带你重识React 中 componentWillRece

    问题: 关于React 中的 的钩子函数 componentWillReceiveProps() 会在什么情况下触...

  • React_新手入门

    React_轻松安装 (跟着小陈,带你玩转React) (热门的三大框架:Angular、React、Vue ) ...

  • react的新生命周期函数

    1.getDerivedStateFromProps 这个生命周期函数是为了替代componentWillRece...

  • 重识iOS之Property

    重识iOS之Property 重识iOS之Property

  • 一步步搭建react后台系统

    手摸手带你撸react后台管理系统 项目地址: react后台系统 创建项目 使用create-react-app...

  • 重识

    输入,我是王婷。发送…… 她后悔了。 男主叫平安,姓江,是的,意思是将来会平安。女主叫王婷。俩人5岁就认识了...

  • 重识

    想和你重新认识傩次 从你叫什么名字说起

  • 重识

    “天空,天是空的”。这句诗让我激动不已。他太特别,几乎要颠覆我所有在课堂里学到得的知识和概念。天是空的!正...

  • 重识Activity-Activity任务栈和启动模式

    本篇文章是《重识Activity》系列的第4篇。 下面是《重识Activity》系列的其他文章: 第1篇:重识Ac...

  • Runtime好文

    重识 Objective-C Runtime - Smalltalk 与 C 的融合重识 Objective-C ...

网友评论

    本文标题:一分钟带你重识React 中 componentWillRece

    本文链接:https://www.haomeiwen.com/subject/zsqdsctx.html