类组件到功能组件

时间:2020-04-09 02:53:45

标签: reactjs react-hooks react-functional-component

如何将此类组件转换为功能组件? 我想要实现的是使用useEffect()订阅和取消订阅Firebase

class PostsProvider extends Component {
  state = { posts: [] }

  unsubscribeFromFirestore = null;

  componentDidMount = () => {
    this.unsubscribeFromFirestore = firestore
      .collection('posts')
      .onSnapshot(snapshot => {
        const posts = snapshot.docs.map(collectIdAndDocs);
        this.setState({ posts });
      });
  }

  componentWillUnmount = () => {
    this.unsubscribeFromFirestore();
  }

1 个答案:

答案 0 :(得分:2)

这就是我转换组件的方式。您可以使用useState()创建发布状态,然后移动useEffect就非常简单了。您要确保的主要事情是,您的依赖项数组正确无误,因此它不会过多(或不够频繁)进行订阅和取消订阅。

function PostsProvider(){
    const [posts,setPosts] = useState([]);
    useEffect(() => {
        const unsubscribeFromFirestore = firestore
        .collection('posts')
        .onSnapshot(snapshot => {
        const posts = snapshot.docs.map(collectIdAndDocs);
        setPosts(posts);
        });
        return () => {
            unsubscribeFromFirestore();
        }
    }, [])
}