首页 > 解决方案 > 传递数据时如何写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)

标签: redux

解决方案


请参阅连接:使用 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
  }

推荐阅读