使用redux将图像状态存储在组件A中,并在组件B中进行获取以响应本机

时间:2019-08-02 20:29:07

标签: javascript reactjs react-native redux react-redux

我正在使用世博相机,并且试图存储拍摄的图像并将其作为个人资料图片传递到另一个屏幕。但是我似乎无法弄清楚。我对redux大致陌生,我不确定自己是否做得对。请在下面查看我的代码

ImageReducer.js

  import { ADD_IMAGE } from '../actions/types';

  const initialState = {
    latestImage: null,
  };

  const ImageReducer = (state = initialState, action) => {
    switch (action.type) {
      case ADD_IMAGE:
        return {
          ...state,
          url: action.url
        };

      default:
        return state;

    }
  };

  export default ImageReducer;

ProfileImageAction.js

  import { ADD_IMAGE} from './types';

  export const ProfileImageAction = (url) => {
    return {
      type: ADD_IMAGE,
      url
    };
  };

reducers / index.js

    import { combineReducers } from 'redux';
    import ImageReducerfrom './ImageReducer';

    export default combineReducers({
      image: ImageReducer
    });

TakePicture.js

    import { Camera, Permissions } from 'expo';
    import { connect } from 'react-redux';
    import { ProfileImageAction } from '../../../../.././src/actions';

    class TakePicture extends Component {

      constructor(props) {
        super(props);
        this.state = {
          hasCameraPermission: null,
          type: Camera.Constants.Type.back,
          latestImage: null
        };
      }


      takePicture = async (latestImage) => {
        if (this.camera) {
          console.log('');

          const photo = await this.camera.takePictureAsync({ base64: true });

          this.setState({
            foo: Math.random()
          });

          const formData = new FormData();
          formData.append('image', photo.base64);
          formData.append('type', 'base64');

          this.setState({
            latestImage: photo.uri,
            isCameraVisible: false
          });
      }

      this.props.dispatch(ProfileImageAction (latestImage));
      };

    render() {
      return (
        .....
      );
    } }

    const mapStateToProps = ({ state }) => {
      return {
        image: state
      };
    };


    export default connect(mapStateToProps, { ProfileImageAction })(TakePicture);

ImageContainer.js

     import { connect } from 'react-redux';

    class ImageContainer extends Component {

      render() {
        console.log(this.props);
        return (

                      <View style={styles.imageContainer}>
                        <Image
                          style={styles.imageStyle}
                          source={this.props.profilePicture}
                        />
                      </View>
                  )

                }

              }
    function mapStateToProps(state) {
      return {
        profilePicture: state.profilePicture
      };
    }

    export default connect(mapStateToProps, null)(ImageContainer);

0 个答案:

没有答案