使用mapDispatchToProps将当前状态从一个屏幕传递到另一个屏幕

时间:2019-08-27 19:16:22

标签: react-native redux react-redux react-native-maps

我正在使用React本机地图和React本机地理编码,我想使用mapDispatchToProps将当前用户位置传递给Redux存储,并希望能够在其他地图组件上使用该位置。我大概是redux世界中的新手,我有点困惑。请对我的代码进行更正。我尝试使用文档中实现的示例,但是,我不完全理解

位置1

    import React, { Component, Fragment } from 'react';
    import {
        View,
        Text,
        StyleSheet,
        TouchableOpacity,
      } from 'react-native';
    import { connect } from 'react-redux';
    import MapView from 'react-native-maps';
    import Geocoder from 'react-native-geocoding';


      Geocoder.init('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');


      const LONGITUDEDELTA = 0.0173;
      const LATITUDEDELTA = 0.0174;
      class Location1 extends Component {
        static navigationOptions = {
          header: null,
        }

        constructor(props) {
          super(props);
          this.state = {
            region: null,
          };
          this.handleBack = this.handleBack.bind(this);
        }

        async componentDidMount() {
          this.watchId = navigator.geolocation.watchPosition(
            async ({ coords: { latitude, longitude } }) => {
              const response = await Geocoder.from({ latitude, longitude });
              const address = response.results[0].formatted_address;
              const location = address.substring(0, address.indexOf(','));

              this.setState({
                location,
                region: {
                  latitude,
                  longitude,
                  title: location,
                  latitudeDelta: LATITUDEDELTA,
                  longitudeDelta: LONGITUDEDELTA,
                },
              });
            }, //sucesso

            () => {}, //erro
            {
              timeout: 2000,
              enableHighAccuracy: true,
              maximumAge: 1000
            }
          );
        }

        componentWillUnmount() {
          navigator.geolocation.clearWatch(this.watchId);
        }


        render() {
          const { region } = this.state;
          const { container, map, } = styles;

          return (
              <View style={container}>
                <MapView
                  style={map}
                  region={region}
                  loadingEnabled
                  showsCompass
                  showsTraffic
                  showsBuildings
                  showsIndoors
                >

                </MapView>

              </View>
          );
        }
      }

      const styles = StyleSheet.create({
        container: {
          flex: 1,
        },
        map: {
          ...StyleSheet.absoluteFill,
        },
      });

      function mapDispatchToProps(dispatch) {
        return {
          region: () => {
            dispatch(this.state.region);
          },
          location: () => {
            dispatch(this.state.location); // address name
          }
        }
      }

      export default connect(mapDispatchToProps) (Location1);

Location2

    import React, { Component, Fragment } from 'react';
    import {
        View,
        Text,
        StyleSheet,
        TouchableOpacity,
      } from 'react-native';
    import { connect } from 'react-redux';
    import MapView from 'react-native-maps';
    import Geocoder from 'react-native-geocoding';



      const LONGITUDEDELTA = 0.0173;
      const LATITUDEDELTA = 0.0174;
      class Location2 extends Component {
        static navigationOptions = {
          header: null,
        }

        constructor(props) {
          super(props);
          this.state = {
            region: null,
          };
        }

        render() {
          const { container, map, } = styles;

          return (
              <View style={container}>
                <MapView
                  style={map}
                  region={this.props.region}
                  loadingEnabled
                  showsCompass
                  showsTraffic
                  showsBuildings
                  showsIndoors
                >
                </MapView>
                  <View><Text>{this.props.location}</Text></View>

              </View>
          );
        }
      }

      const styles = StyleSheet.create({
        container: {
          flex: 1,
        },
        map: {
          ...StyleSheet.absoluteFill,
        },
      });

      function mapStateToProps(state) {
        return {
          region: state.region,
          location: state.location
        }
      }

      export default connect(mapStateToProps) (Location2);

减速器

import { CURRENT_LOCATION, LOCATION_NAME } from '../actions/types';

            const initialState = {
              region: null,
              location: ''
            };

            const Reducer = (state = initialState, action) => {
              switch (action.type) {
                case CURRENT_LOCATION:
                  return {
                    ...state,
                    region: action.region
                  };
                case LOCATION_NAME:
                  return {
                    ...state,
                    location: action.location
                  };
                default:
                  return state;


              }
            };

            export default Reducer;

1 个答案:

答案 0 :(得分:0)

首先在这里的第一个代码中

function mapDispatchToProps(dispatch) {
    return {
      region: () => {
        dispatch(this.state.region);
      },
      location: () => {
        dispatch(this.state.location); // address name
      }
    }
  }

  export default connect(mapDispatchToProps) (Location1);

您需要传递第一个参数来连接,这是mapStateToProps,但是如果您不想使用它,请传递null代替

export default connect(mapStateToProps, mapDispatchToProps)(Location1);

您还可以通过传递和actionType(必需)和actionPayload(可选)在redux中分派动作

 function mapDispatchToProps(dispatch) {
    return {
      region: (regionVal) => {
        dispatch({type: 'LOCATION_NAME',payload: regionVal});
      },
      location: (locationVal) => {
        dispatch({type: 'CURRENT_LOCATION',payload: locationVal}); // address name
      }
    }}

并像

一样在componentDidMount内部调用它
async componentDidMount() { 
.
.
.
  this.props.region(regionVal);
  this.props.locatio(locationVal);
}

在减速器中,您应该解决此问题

            case CURRENT_LOCATION:
              return {
                ...state,
                region: action.region
              };

像这样

            case CURRENT_LOCATION:
              return {
                ...state,
                region: action.payload // you should call the payload from the action
              };