簡體   English   中英

基於redux狀態有條件地在組件中調用函數的方式和位置

[英]How and where call function in component conditionally based on redux state

我有一個組件,在我的組件中,我有一些子組件。

在我的父組件中,我有一些功能,我想從子組件中觸發它。 所以我用redux做到了。

這是我的父組件:

   import React, { Component } from "react";
    import { withRouter } from "react-router-dom";
    import { bindActionCreators } from "redux";
    import { splashStop } from "store/actions/Home/splashStop";

import { connect } from "react-redux";

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
    this.goPage = this.goPage.bind(this);
  }

  componentDidMount() {
  }

  goPage = () => {
     this.props.history.push("/agencies");
  };

  render() {
    if (this.props.homeSplash.splashStart == true) {
      myTime.play();
    }
    return (
      <div>
         <ChildComponent />
      </div>
    );
  }
}

const mapStateToProps = state => ({
  homeSplash: state.homeSplash
});

function mapDispatchToProps(dispatch) {
  return {
    splashStop: bindActionCreators(splashStop, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(Home));

這是我的孩子部分:

這是在我的子組件的onClick函數中,我調度了redux操作:

  triggerSplash = () => {
    this.props.splashStart();
  };

我的動作:

export const START_SPLASH =“ START_SPLASH”;

export const splashStart = () => {
    return dispatch => {
        dispatch({
            type: START_SPLASH,
            payload: true
          });
    };
  };

和我的減速器:

import { START_SPLASH } from "store/actions/Home/splashStart";

let initialState = {
  splashStart: false
};

export default (state = initialState, action) => {
  switch (action.type) {
    case START_SPLASH:
      return { ...state, splashStart: action.payload };
    default:
      return state;
  }
};

我的減速器,動作正常。

這是我不知道為什么myTime.play(); 組件安裝時始終可以正常工作,而無需關心此控件:

if (this.props.homeSplash.splashStart == true) {
          myTime.play();
        }

我把它放到錯誤的地方還是什么?

在您的redux結構中,似乎一切正常。 但是您也應該提供childComponent使其更加清晰。
如果您在子組件中正確連接了redux操作,請嘗試以下操作:

<button ... onClick={() => this.triggerSplash()}>Click</button>

將箭頭功能放在onClick 因為在組件初始化中,所有組件函數都會在渲染時自動調用。

暫無
暫無

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

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