有没有办法知道渲染函数是因为父修改(props)还是因为内部状态发生了变化而被调用?

IT技术 reactjs
2021-05-25 12:09:23

我是 React 的新手,

我想知道是否有任何方法可以知道是因为父修改(props)还是因为内部状态发生了变化而调用了渲染函数?

假设我有一个<input type"text" />. 我希望它的值在 keydown(onChange 函数)或每次 props(来自父级)改变时改变

2个回答

你可以比较你的新旧props和状态:

componentDidUpdate(prevProps, prevState) {
  Object.entries(this.props).forEach(([key, val]) =>
    prevProps[key] !== val && console.log(`${key} prop was changed`)
  );
  Object.entries(this.state).forEach(([key, val]) =>
    prevState[key] !== val && console.log(`${key} state changed`)
  );
}

你可以简单地在渲染函数中添加一个 console.log(this.props) 或 (props) ,它会在控制台上记录props。