React Hooks深度使用心得:从Class组件到函数组件的思维转变

2021年,React Hooks已经发布两年多,但我们团队从Class组件迁移到Hooks的过程并不顺利。这篇文章记录了我们踩过的坑和总结的最佳实践。

思维转变:从生命周期到副作用

最大的挑战不是语法,而是思维模式的转变:

Class组件思维

class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = { user: null, loading: false };
  }
  
  componentDidMount() {
    this.fetchUser();
  }
  
  componentDidUpdate(prevProps) {
    if (prevProps.userId !== this.props.userId) {
      this.fetchUser();
    }
  }
  
  componentWillUnmount() {
    // 清理工作
  }
  
  fetchUser = async () => {
    this.setState({ loading: true });
    try {
      const user = await api.getUser(this.props.userId);
      this.setState({ user, loading: false });
    } catch (error) {
      this.setState({ loading: false, error });
    }
  };
  
  render() {
    // ...
  }
}