![](/img/trans.png)
[英]React-Redux & Material UI: Component doesn't pass store to 'connected' child
[英]ReactTransitionGroup doesn't works with React-redux connected component
我正在做一個更大的項目,但我創建了這個簡短的示例來說明問題。
如果我使用Box
組件,它的工作原理。 當我們單擊按鈕時,它將在控制台中輸出componentWillEnter
和componentWillLeave
。
如果我使用BoxContainer
容器,它將不再起作用。 不調用componentWillEnter
和componentWillLeave
特殊生命周期掛鈎。
{this.state.shouldShowBox && <BoxContainer/>}
Webpack構建正確完成,控制台中沒有錯誤,但是沒有輸出。
我還嘗試了高級API: ReactCSSTransitionGroup
,它可與Box
和BoxContainer
組件一起使用。 但是我需要使用低級API: ReactTransitionGroup
。
您是否知道為什么當我們使用react-redux
時它不起作用?
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將您的組件包裝成一個“ connected”對象,但是,有一些解決方法,例如connect-with-transition-group
Redux的創建者Dan Abramov就此問題發表了這樣的評論
老實說,我不想將對過渡組的支持硬編碼到connect()中。 這是一個非常具體的API,在沒有更好的解決方案之前,它不會成為React動畫API,其作用更像是逃生艙口。 它在嵌套實例上調用實例方法的方式與React概念模型不太吻合。
我建議您:
像您建議的那樣圍繞connect()編寫自己的包裝器
或者使用更友好的React方法制作動畫,例如https://github.com/chenglou/react-motion
像您建議的那樣圍繞connect()編寫您自己的包裝器,或者對https://github.com/chenglou/react-motion等動畫使用更易於使用的方法
我們還嘗試做同樣的事情,將TransitionGroup
與redux
連接的組件連接起來,例如
<TransitionGroup>
layerIds.map(id => ( <Layer ...>))
</TransitionGroup>
其中Layer
本身是連接的Redux組件。
我們還嘗試將Layer
包裹起來
const WrappedLayer = (props) =>{
return <TransitionGroup>
<Layer {...props}/>
</TransitionGroup>
}
並使用WrappedLayer
連接,它將僅在諸如componentWillAppear
和componentDidAppear
掛載階段起作用,而在卸載階段不起作用,因為當您刪除UI上的一個圖層時, TransitionGroup
也將被刪除,那么像componentWillLeave
這樣的生命周期方法將永遠不會被觸發。
好消息是,我們終於找到了一個非常方便的庫react-move
https://github.com/react-tools/react-move ,我們認為它比react-motion
更好,因為我們可以自定義持續時間,動畫曲線,而且非常干凈。
希望這對您有幫助,如果您通過使用react-move
遇到任何問題,請留言。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.