redux - 传递数据时如何写mapDispatchToProps?
问题描述
我在 Redux 上有点挣扎。我正在尝试向 redux 发送一个包含数据的操作 - 我可以发送发送并在没有它的情况下获得成功的响应,那么如何重写代码以便可以发送数据?
我正在使用 RN 图像选择器来选择图像。一旦用户选择了图像(在getPhotoFromGallery
函数中),它将被写入本地状态,然后该本地状态将被传递到 redux 中的函数调度。我收到错误this.props.addImageToPost(imageData) is not a function
class MyForm extends React.Component {
state = {
imageData: null,
caption: null,
base64URI: null
}
//choose the photo.
getPhotoFromGallery = () => {
const { imageData } = this.state
ImagePicker.launchImageLibrary({}, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else {
//send image to redux
this.setState({ imageData: response });
this.setState({ base64URI: response.uri });
this.props.addImageToPost(imageData) // ????
}
});
};
//show image in component
showPickedImage() {
const { imageData } = this.state;
if (imageData !== null) {
return (
<Image
source={{ uri: imageData.uri }}
style={{ alignSelf: 'center', width: 90, height: 90, borderRadius: 20, marginLeft: 15 }}
/>
);
} else {
return (
<View>
<TouchableOpacity
style={{ alignSelf: 'center', width: 90, height: 90, borderRadius: 20, marginLeft: 15, alignItems: 'center', justifyContent: 'center', backgroundColor: 'white', shadowColor: "#000", shadowOffset: { width: 0, height: 5, }, shadowOpacity: 0.2, shadowRadius: 15, }}
onPress={this.getPhotoFromGallery}
>
<Icon name="camera" size={32} color="black" />
</TouchableOpacity>
</View>
);
}
}
render() {
const { image } = this.props;
return (
<View style={styles.myFormContainer}>
{this.showPickedImage()}
</View>
);
}
function mapStateToProps(state) {
return { imageData: state.post.imageData }
}
const mapDispatchToProps = {
addImageToPost, // ????
};
export default connect(mapStateToProps, mapDispatchToProps)(MyForm)
解决方案
请参阅连接:使用 mapDispatchToProps 调度操作。
它应该是这样的
const mapDispatchToProps = dispatch => ({
addImageToPost: (imageData) => dispatch({ type: 'ActionType', payload: imageData })
});
或者如果您有动作创建者
const mapDispatchToProps = dispatch => ({
addImageToPost: (imageData) => dispatch(myActionCreator(imageData))
});
并像这样在您的组件中使用它
else {
//send image to redux
this.setState({ imageData: response });
this.setState({ base64URI: response.uri });
this.props.addImageToPost(imageData); // ???? correct
}
推荐阅读
- javascript - 传播运算符的打字稿抛出错误
- ios - 自动续订和沙盒模式下的收据
- c# - 在 BizTalk 中将取消批处理的消息合并回单个消息
- javascript - 箭头函数与类方法的内存占用
- python - 我想用 z 矩阵的所有值的平均值填充 z 矩阵中的缺失值
- python - Python匹配多个条件
- mysql - MySQL JOIN 仅在使用通配符选择每一列时才能正常工作
- javascript - 通过单击等显示下一个 4 li 的功能,直到 li 结束
- node.js - 如何从参数中获取实体并在 Dialogflow 内联编辑器中创建 if 条件以实现
- php - 为什么 PHP substr 函数返回错误的值?