ReactCSSTransitionGroup componentWillLeave not cal

2020-07-14 05:51发布

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!

2条回答
太酷不给撩
2楼-- · 2020-07-14 06:00

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 />...

查看更多
再贱就再见
3楼-- · 2020-07-14 06:08

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>
        )
    }
}
查看更多
登录 后发表回答