ReactCSSTransitionGroup componentWillLeave not called

别等时光非礼了梦想. 提交于 2019-12-06 02:45:46

问题


Im trying to play around with ReactCssTransition but somehow the event is not called(componentWillLeave)

Here's my component

import React, { Component } from 'react'
import TransitionGroup from 'react-addons-css-transition-group'

export default class TransitionComponent extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      let {componentKey} = this.props
      <TransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={500}>
        <Item key={"item"+componentKey} />
      </TransitionGroup>
    );
  }
}

And the child component

class Item extends Component {

  componentDidEnter() {
    console.log("component did enter");
  }

  componentWillLeave(callback) {
    console.log("component will leave");
  }

  render() {
    return (
      <div>Item</div>
    )
  }
}

Any clue? Thanks!


回答1:


I had similar issue caused by not calling the callback within the "componentWillEnter" function. Quote from React documentation

It will block other animations from occurring until callback is called

class Item extends Component {

    componentWillEnter(callback) {
        console.log("component will enter");
        callback();
    }

    componentDidEnter() {
        console.log("component did enter");
    }

    componentWillLeave(callback) {
        console.log("component will leave");
        callback();
    }

    render() {
        return (
            <div>Item</div>
        )
    }
}



回答2:


Please excuse me as I am new to React myself but my understanding is that when components are mounted/unmounted you will not get the componentDidEnter() and componentWillLeave() lifecycle hooks.

All you have at your disposal is componentDidMount() and componentWillUnmount().

So replace the above portion with this and you should see your console logs:

  componentDidMount() {
    console.log('Component did mount');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

I believe if you want access to all of the lifecycle hooks you need to use ReactTransitionGroup instead, I have not yet figured out how to implement this though.

There is a good article on it on Medium though where the author explains it quite well.

There is a bit in the article where she talks about wrapping her child component with the ReactTransitionGroup component and I believe that is what you are looking for. Basically wrapping it around your current <Item />...



来源:https://stackoverflow.com/questions/35803344/reactcsstransitiongroup-componentwillleave-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!