javascript - React Hook 的 componentWillReceiveProps、componentDidUpdate

标签 javascript reactjs react-hooks

我遇到两个挑战:

  • 即使根据 React 指南,不鼓励使用派生状态,但某些边缘情况仍然需要它。
    就带有 React Hook 的功能组件而言,React Hook 的等效实现是什么,如果我确实需要类组件中的派生状态,将在每个父渲染的 componentWillReceiveProps 中更新

请参阅下面的代码示例:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: props.count > 100 ? 100 : props.count,
    }

  }

  /*What is the equivalent implementation when React Hook is used here componentWillReceiveProps*/
  componentWillReceiveProps(nextProps) {
    if (nextProps.count !== this.props.count) {
      this.setState({
        count: nextProps.count > 100 ? 100 : nextProps.count
      });
    }
  }

  render() {
    return ( <
      div > {
        this.state.count
      } <
      /div>
    );
  }
}

export default App;

  • 至于componentDidUpdate,在使用React Hook时,componentDidUpdate有它的对应部分,你必须像这样使用它,

      React.useEffect(() => {
        return () => {
    
         };
      }, [parentProp]);
    

    useEffect 的第二个参数确保仅当 prop 更改时才执行代码,但是如果我想根据多个相应的 prop 更改执行相应的任务怎么办?如何使用 useEffect 完成它?

请参阅下面的代码示例:

class App extends Component {


  /*What is the equivalent implementation when functional component with React Hook is used here */
  componentDidUpdate(prevProps, prevState) {
    if (prevProps.groupName !== this.props.groupName) {
      console.log('Let'
        's say, I do want to do some task here only when groupName differs');
    } else if (prevProps.companyName !== this.props.companyName) {
      console.log('Let'
        's say, I do want to do some different task here only when companyName differs');
    }

  }


  render() {
    /*for simplicity, render code is ignored*/
    return null;
  }
}

export default App;

最佳答案

可以使用 useEffect 钩子(Hook)来完成与旧的 componentWillReceive 属性等效的 React 钩子(Hook),只需指定我们想要监听依赖项数组中的更改的属性即可。

即:

export default (props) => {

    useEffect( () => {
        console.log('counter updated');
    }, [props.counter])

    return <div>Hi {props.counter}</div>
}

对于componentDidUpdate,只需省略依赖数组,useEffect函数将在每次重新渲染后调用。

即:

export default (props) => {

    useEffect( () => {
        console.log('counter updated');
    })

    return <div>Hi {props.counter}</div>
}

关于javascript - React Hook 的 componentWillReceiveProps、componentDidUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54843675/

相关文章:

javascript - 是否有一种非天真的方法来计算 DOM 偏移量的逻辑偏移量?

reactjs - 使用 react-testing-library 测试 useContext()

javascript - 状态未使用 React hook 更新

reactjs - 使用 React hooks 时如何初始化第三方库?

javascript - 我正在尝试使用 react 钩子(Hook) useContext() 但它不起作用

Javascript "pre set"一个变量?

php - 第一个主体 onload 函数或 PHP 会发生什么?

json - 如何使用 Go 后端和 ReactJS 前端在 MongoDB 中插入 markdown 代码

node.js - create-react-app my-app redux 与 new react 18.0.0 的错误

javascript - 如何从工厂函数返回 React 内存回调