函数式React Native组件可调用Redux Action,类组件不行
类组件调用Redux Action的错误分析与修复
你的类组件存在三个关键错误,导致Redux Action无法正常触发:
1. mapDispatchToProps写法错误
你直接调用mapDispatchToProps()传给connect,但这个函数没有接收dispatch参数,也没有将action与dispatch绑定。正确的写法有两种:
- 直接传递包含action的对象,
connect会自动帮你绑定dispatch; - 写成接收
dispatch参数的函数,返回绑定后的action调用函数。
2. Button点击事件错误
React Native的Button组件触发点击的属性是onPress,而非Web端的onClick;同时你直接写onPress={this.props.updateNumPosInCode(4)}会导致组件渲染时立即执行该方法,而非点击按钮时触发,必须用箭头函数包裹或者提前绑定。
3. mapStateToProps取值路径错误
函数式组件中你取的是store.gameplay.numPosInCode,但类组件的mapStateToProps直接取state.numPosInCode,路径不匹配,应该修正为state.gameplay.numPosInCode。
修正后的完整代码
import * as React from 'react'; import {View, StyleSheet, Button, Text} from 'react-native'; import {connect} from 'react-redux'; import {updateNumPosInCode} from './redux/actions/gameplayAction'; class ColourBoard extends React.Component { constructor(props) { super(props); this.state = { top: 0, // 初始化top属性,避免样式报错 numPosInCode: 5, }; } render() { return ( <View style={[ styles.MainContainer, { top: this.state.top, }, ]}> <Button onPress={() => this.props.updateNumPosInCode(4)} title="Test" color="#841584" /> {/* 添加文本显示当前值,方便验证修改是否生效 */} <Text style={{marginTop: 20}}>当前位数:{this.props.numPosInCode}</Text> </View> ); } } const mapStateToProps = state => ({ numPosInCode: state.gameplay.numPosInCode, }); // 推荐写法:直接传递action对象,connect自动绑定dispatch const mapDispatchToProps = { updateNumPosInCode, }; // 也可以用函数式写法(效果一致): // const mapDispatchToProps = (dispatch) => ({ // updateNumPosInCode: (num) => dispatch(updateNumPosInCode(num)) // }); const styles = StyleSheet.create({ MainContainer: { left: 1, justifyContent: 'center', alignItems: 'center', height: '100%', width: '100%', position: 'absolute', zIndex: 1, }, }); export default connect(mapStateToProps, mapDispatchToProps)(ColourBoard);
内容的提问来源于stack exchange,提问作者Dave Chambers
相关产品推荐
相关产品推荐

