React TransitionGroup 不会在状态更改时卸载子项
React TransitionGroup not unmounting children on state change
我正在使用 React Transition Group 构建侧边栏组件。相关代码如下:
function FirstChild(props) {
const childrenArray = React.Children.toArray(props.children);
return childrenArray[0] || null;
}
class Sidebar extends Component {
componentWillEnter(cb) { console.log('entering'); cb() }
componentWillLeave(cb) { console.log('leaving'); cb() }
render() {
// return sidebar jsx
}
}
class Nav extends Component {
...
toggleSidebar() {
const newState = !this.state.show;
this.setState({ show: newState })
}
render() {
return (
<TransitionGroup component={FirstChild}>
{ (this.state.show == true) ? <Sidebar /> : null }
</TransitionGroup>
)
}
}
问题是,当我尝试切换侧边栏时,none 的生命周期挂钩被触发。第一次点击时,侧边栏被添加到 DOM 并且调用了 componentDidMount 而不是 componentWillEnter。当我再次单击以隐藏它时,state.show 被正确设置为 false,但侧边栏没有隐藏并且这次没有触发生命周期挂钩。
我想知道我是否正确地执行了三元运算符以有条件地渲染边栏,或者原因是否是因为我只在 TransitionGroup 下渲染一个子级(为此,我使用了 FirstChild method found here)。
问题出在呈现逻辑中。出于某种原因
{ (this.state.show == true) ? <Sidebar /> : null }
不会触发 ComponentWillEnter / ComponentWillLeave 等 TransitionGroup 生命周期函数,而是将其更改为
{ this.state.show && <Sidebar }
修复了这个问题。
我正在使用 React Transition Group 构建侧边栏组件。相关代码如下:
function FirstChild(props) {
const childrenArray = React.Children.toArray(props.children);
return childrenArray[0] || null;
}
class Sidebar extends Component {
componentWillEnter(cb) { console.log('entering'); cb() }
componentWillLeave(cb) { console.log('leaving'); cb() }
render() {
// return sidebar jsx
}
}
class Nav extends Component {
...
toggleSidebar() {
const newState = !this.state.show;
this.setState({ show: newState })
}
render() {
return (
<TransitionGroup component={FirstChild}>
{ (this.state.show == true) ? <Sidebar /> : null }
</TransitionGroup>
)
}
}
问题是,当我尝试切换侧边栏时,none 的生命周期挂钩被触发。第一次点击时,侧边栏被添加到 DOM 并且调用了 componentDidMount 而不是 componentWillEnter。当我再次单击以隐藏它时,state.show 被正确设置为 false,但侧边栏没有隐藏并且这次没有触发生命周期挂钩。
我想知道我是否正确地执行了三元运算符以有条件地渲染边栏,或者原因是否是因为我只在 TransitionGroup 下渲染一个子级(为此,我使用了 FirstChild method found here)。
问题出在呈现逻辑中。出于某种原因
{ (this.state.show == true) ? <Sidebar /> : null }
不会触发 ComponentWillEnter / ComponentWillLeave 等 TransitionGroup 生命周期函数,而是将其更改为
{ this.state.show && <Sidebar }
修复了这个问题。