簡體   English   中英

ReactTransitionGroup不適用於React-redux連接的組件

[英]ReactTransitionGroup doesn't works with React-redux connected component

我正在做一個更大的項目,但我創建了這個簡短的示例來說明問題。

如果我使用Box組件,它的工作原理。 當我們單擊按鈕時,它將在控制台中輸出componentWillEntercomponentWillLeave

如果我使用BoxContainer容器,它將不再起作用。 不調用componentWillEntercomponentWillLeave特殊生命周期掛鈎。

{this.state.shouldShowBox && <BoxContainer/>}

Webpack構建正確完成,控制台中沒有錯誤,但是沒有輸出。

我還嘗試了高級API: ReactCSSTransitionGroup ,它可與BoxBoxContainer組件一起使用。 但是我需要使用低級API: ReactTransitionGroup

您是否知道為什么當我們使用react-redux時它不起作用?

使用的版本:

  • 反應: 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將您的組件包裝成一個“ connected”對象,但是,有一些解決方法,例如connect-with-transition-group

Redux的創建者Dan Abramov就此問題發表了這樣的評論

老實說,我不想將對過渡組的支持硬編碼到connect()中。 這是一個非常具體的API,在沒有更好的解決方案之前,它不會成為React動畫API,其作用更像是逃生艙口。 它在嵌套實例上調用實例方法的方式與React概念模型不太吻合。

我建議您:

像您建議的那樣圍繞connect()編寫您自己的包裝器,或者對https://github.com/chenglou/react-motion等動畫使用更易於使用的方法

我們還嘗試做同樣的事情,將TransitionGroupredux連接的組件連接起來,例如

<TransitionGroup>
  layerIds.map(id => ( <Layer ...>))
</TransitionGroup>

其中Layer本身是連接的Redux組件。

我們還嘗試將Layer包裹起來

const WrappedLayer = (props) =>{
  return <TransitionGroup>
  <Layer {...props}/>
  </TransitionGroup>
}

並使用WrappedLayer連接,它將僅在諸如componentWillAppearcomponentDidAppear掛載階段起作用,而在卸載階段不起作用,因為當您刪除UI上的一個圖層時, TransitionGroup也將被刪除,那么像componentWillLeave這樣的生命周期方法將永遠不會被觸發。

好消息是,我們終於找到了一個非常方便的庫react-move https://github.com/react-tools/react-move ,我們認為它比react-motion更好,因為我們可以自定義持續時間,動畫曲線,而且非常干凈。

希望這對您有幫助,如果您通過使用react-move遇到任何問題,請留言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM