我正在使用 react-native 学习 redux,我正在尝试使用“容器组件”模式中的操作。
我想在我的组件中调用一个 redux 操作,我正在使用 mapDispatchToProps
来执行此操作。
但是当组件调用 Action 时,我得到了著名的红屏
this.props.myDecrementor is not a function
当我在我的组件中调试和 console.log(this.props)
时,没有可用的操作或 Prop 。
让我展示一下我的代码:
myContainer.js
import { connect } from "react-redux";
import { incrementStepCount, decrementStepCount } from "../actions";
class ChooseHour extends Component {
constructor(props) {
super(props);
this.addStep = this.addStep.bind(this);
this.removeStep = this.removeStep.bind(this);
}
addStep() {
this.props.myIncrementor();
}
removeStep() {
this.props.myDecrementor();
}
render() {
return ( <
View style = {
{
flex: 1
}
} >
<
Button onPress = {
this.addStep
}
style = {
styles.btnAddEtape
}
small transparent iconLeft >
<
Text > Add Step < /Text> <
/Button> <
InputStep key = {
1
}
label = "MyStep" / >
<
/View>
);
}
}
function mapStateToProps(state) {
return {
order: state.order
};
}
function mapDispatchToProps(dispatch) {
return {
myDecrementor: () => dispatch(decrementStepCount()),
myIncrementor: () => dispatch(incrementStepCount())
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(ChooseHour);
我的组件.js
export default class InputStep extends Component {
decrementStepCountinComponent() {
this.props.myDecrementor();
}
render() {
return ( < Item style = {
styles.inputContainer
}
inlineLabel > < Label > {
this.props.label
} < /Label> <
Input style = {
styles.input
}
placeholder = "Step" / > < Icon name = "times"
type = "FontAwesome"
style = {
{
color: "red"
}
}
onPress = {
() => this.decrementStepCountinComponent()
}
/> < /
Item > );
}
}
在容器中调用操作有效,但在组件中无效 ... 我读过这篇文章 What is mapDispatchToProps?但我真的不明白为什么它不起作用。
预先感谢您的帮助。
最佳答案
您需要将 myDecrement() 函数作为 props 从容器传递给 inputstep 组件。
在我的容器中添加
<InputStep myDecrementor = {this.props.myDecrementor}
关于javascript - 无法在我的组件中调用 redux 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50869887/