Почему реквизиты не меняются в зависимости от состояния карты на реквизиты в React Redux - PullRequest
3 голосов
/ 02 февраля 2020

Я обновил свой магазин с помощью mapDispatchToProps следующим образом:

function mapDispatchToProps(dispatch){ 
  return{
    addFirstImageUrl: (firstUrl) => dispatch({
      type: "ADD_FIRST_IMAGE_URL",
      firstUrl
    })
  }
}

Я знаю, что это работает, потому что когда я запускаю mapStateToProps, я регистрирую состояние следующим образом:

function mapStateToProps(state){
  console.log(state)
  return{
    firstImageUrl: state.firstImageUrl
  }
}

This возвращает:

}
Object {
  "posts": Object {
    "firstImageTitle": "",
    "firstImageUrl": "https://firebasestorage.MYURL",
    "secondImageTitle": "",
    "secondImageUrl": "",
  },
}

, однако, когда я звоню this.props.firstImageUrl, возвращается неопределенное значение. Я чувствую, что это должно возвратить URL выше, это неправильное мышление?

компонентная функция:

uploadImage = async (uri) => {
    const response = await fetch(uri);
    const blob = await response.blob();
    var ref = firebase
      .storage()
      .ref()
      .child(new Date().toString());
    const snapshot = await ref.put(blob)
    const url = await snapshot.ref.getDownloadURL();
    this.props.addFirstImageUrl(url);
    console.log("First Image Url: " + this.props.firstImageUrl)
  };
import React from "react";
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from "react-native";
import { Camera } from "expo-camera";
import * as Permissions from "expo-permissions";
import { FontAwesome } from "@expo/vector-icons";
import * as firebase from "firebase";
import { connect } from "react-redux";
import { addFirstImageUrl } from "../store/actions/posts";
import { bindActionCreators } from "redux";

function mapStateToProps(state){
  console.log(state)
  return{
    firstImageUrl: state.firstImageUrl
  }
}

function mapDispatchToProps(dispatch){ 
  return{
    addFirstImageUrl: (firstUrl) => dispatch({
      type: "ADD_FIRST_IMAGE_URL",
      firstUrl
    })
  }
}

class FirstCameraScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasCameraPermissions: null,
      type: Camera.Constants.Type.back,
      isFlashLIghtOn: Camera.Constants.FlashMode.off,
      firstImageUrl: " "
    };
  }

  static navigationOptions = {
    title: "FirstCamera"
  };

  //ask for camera permission
  async componentDidMount() {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({
      hasCameraPermissions: status === "granted"
    });
  }

  // Flip the camera
  flipCamera = () => {
    this.setState({
      type:
        this.state.type === Camera.Constants.Type.back
          ? Camera.Constants.Type.front
          : Camera.Constants.Type.back
    });
  };

  //Toggle Flashlight
  flashLight = () => {
    this.setState({
      isFlashLIghtOn:
        this.state.isFlashLIghtOn === Camera.Constants.FlashMode.off
          ? Camera.Constants.FlashMode.on
          : Camera.Constants.FlashMode.off
    });
  };

  //Take Picture and send to home
  takePicture = async () => {
    if (this.camera) {
      let photo = await this.camera.takePictureAsync();
      if (!photo.cancelled) {
        await this.uploadImage(photo.uri);
      }
      this.props.navigation.navigate("FirstNamingScreen");
    }
  };

  uploadImage = async (uri) => {
    const response = await fetch(uri);
    const blob = await response.blob();
    var ref = firebase
      .storage()
      .ref()
      .child(new Date().toString());
    const snapshot = await ref.put(blob)
    const url = await snapshot.ref.getDownloadURL();
    this.props.addFirstImageUrl(url);
    console.log("First Image Url: " + props.posts)
  };

  render() {
    const { hasCameraPermissions } = this.state;
    const { navigate } = this.props.navigation;
    if (hasCameraPermissions === null) {
      return <View />;
    } else if (hasCameraPermissions === false) {
      return (
        <View>
          <Text>No access to Camera</Text>
        </View>
      );
    } else if (hasCameraPermissions === true) {
      return (
        <View style={styles.container}>
          <Camera
            style={styles.cameraView}
            type={this.state.type}
            flashMode={this.state.isFlashLIghtOn}
            ref={ref => {
              this.camera = ref;
            }}
          >
            <View style={styles.actionContainer}>
              <TouchableOpacity
                onPress={() => this.flipCamera()}
                style={styles.iconHolder}
              >
                <FontAwesome name="camera" size={35} style={styles.icon} />
              </TouchableOpacity>
              <TouchableOpacity
                onPress={() => {
                  this.takePicture();
                }}
                style={styles.iconHolder}
              >
                <FontAwesome name="circle" size={35} style={styles.icon} />
              </TouchableOpacity>
              <TouchableOpacity
                onPress={() => this.flashLight()}
                style={styles.iconHolder}
              >
                <FontAwesome name="flash" size={35} style={styles.icon} />
              </TouchableOpacity>
            </View>
          </Camera>
        </View>
      );
    }
  }
}


export default connect(mapStateToProps, mapDispatchToProps)(FirstCameraScreen)

1 Ответ

2 голосов
/ 02 февраля 2020

Измените mapStateToProps на это.

function mapStateToProps(state) {
  console.log(state);
  return {
    firstImageUrl: state.posts.firstImageUrl
  };
}

И ваш uploadImage метод.

  uploadImage() {
    const response = await fetch(uri);
    const blob = await response.blob();
    var ref = firebase
      .storage()
      .ref()
      .child(new Date().toString());
    const snapshot = await ref.put(blob);
    const url = await snapshot.ref.getDownloadURL();
    this.props.addFirstImageUrl(url);
    console.log("First Image Url: " + this.props.firstImageUrl);
  };

конструктор

constructor(props) {
    super(props);
    this.uploadImage = this.uploadImage.bind(this);
    this.state = {
      hasCameraPermissions: null,
      type: Camera.Constants.Type.back,
      isFlashLIghtOn: Camera.Constants.FlashMode.off,
      firstImageUrl: " "
    };
  }
...