一分钟带你重识React 中 componentWillReceiveProps() skr~~

问题: 关于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 (
    
父组件:{this.state.privateData}
); } } interface PropsType { data: number[]; } class SubComponent extends React.Component { constructor(props: any) { super(props); } componentWillReceiveProps(nextProps: PropsType) { console.log(nextProps, "componentWillReceiveProps"); } render() { return
子组件:{this.props.data}
; } } export default App;

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

你可能感兴趣的:(一分钟带你重识React 中 componentWillReceiveProps() skr~~)