我正在开发一个更大的项目,但我创建了这个简短的示例来说明问题。
如果我使用 Box
组件,它就可以工作。它在控制台 componentWillEnter
中输出并且
当我们点击按钮时componentWillLeave
。
如果我使用 BoxContainer
容器,它就不再工作了。不会调用 componentWillEnter
和 componentWillLeave
特殊生命周期 Hook 。
{this.state.shouldShowBox && <BoxContainer/>}
Webpack 构建正确完成,控制台中没有错误,但它没有输出任何内容。
我还尝试了高级 API:ReactCSSTransitionGroup
,它可以与 Box
和 BoxContainer
组件配合使用。但我需要使用低级 API:ReactTransitionGroup
。
你知道为什么当我们使用react-redux
时它不起作用吗?
使用的版本:
- react :15.0.2
- redux:3.5.2
- react-redux:4.4.5
代码:
import React from 'react';
import {render} from 'react-dom';
import {Provider, connect} from 'react-redux';
import {createStore, compose, combineReducers} from 'redux';
import TransitionGroup from 'react/lib/ReactTransitionGroup';
// Box component
class Box extends React.Component {
componentWillEnter(callback) {
console.log('componentWillEnter');
callback();
}
componentWillLeave(callback) {
console.log('componentWillLeave');
callback();
}
render() {
return <div className="box"/>;
}
}
// Boxe connected component
const BoxContainer = connect(null, {})(Box);
// App component
class App extends React.Component {
state = {
shouldShowBox: true
};
toggleBox = () => {
this.setState({
shouldShowBox: !this.state.shouldShowBox
});
};
render() {
return (
<div>
<TransitionGroup>
{this.state.shouldShowBox && <BoxContainer/>}
</TransitionGroup>
<button className="toggle-btn" onClick={this.toggleBox}>
toggle
</button>
</div>
);
}
}
// reducer
function reducer(state = [], action) {
switch (action.type) {
default:
return state
}
}
// store
const store = createStore(reducer);
// render
render(
<Provider store={store}>
<App />
</Provider>
,
document.getElementById('root')
);
最佳答案
这不应该起作用,因为 connect 将您的组件包装到“连接”对象中,但是,有一些解决方法,例如 connect-with-transition-group
Redux 的创建者 Dan Abramov 曾这样说过 issue
To be completely honest I don’t want to hardcode supports for transition groups into connect(). This is a very specific API that is not going to be the React animation API and acts more like an escape hatch until there are better solutions. The way it invokes instance methods on a nested instance does not align with React conceptual model very well.
I would suggest you to:
Either write your own wrapper around connect() like you suggested
Or use a more React-friendly approach to animations such as https://github.com/chenglou/react-motion
Either write your own wrapper around connect() like you suggested Or use a more React-friendly approach to animations such as https://github.com/chenglou/react-motion
关于javascript - ReactTransitionGroup 不适用于 React-redux 连接组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37092116/