首页 > 解决方案 > 在组件 A 中使用 redux 存储图像状态并在 react native 中获取组件 B

问题描述

我正在使用 expo 相机,我正在尝试存储拍摄的图像并将其作为个人资料图片传递到另一个屏幕。但是我似乎无法弄清楚。我对 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
    };
  };

减速器/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);

标签: javascriptreactjsreact-nativereduxreact-redux

解决方案


推荐阅读