[英]How to display a snackbar conditionally based on redux state using thunks?
[英]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.