【问题标题】:passing current state from one screen to another using mapDispatchToProps使用 mapDispatchToProps 将当前状态从一个屏幕传递到另一个屏幕
【发布时间】:2019-08-27 19:16:22
【问题描述】:

我正在使用 react native 地图和 react native 地理编码,我想使用 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);

位置2

    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;

【问题讨论】:

  • 如果不仔细查看您的代码,您就没有使用 react-redux 的 connect HOC。您正在导入它,而不使用它。 IE 导出默认连接(mapStateToProps, mapDispatchToProps)(Location2); react-redux.js.org/api/connect
  • 为我在原始代码中使用它的错误道歉,这是一个错误进行更正
  • 你不能使用connect(mapDispatchToProps),你需要先传递一个mapStateToProps,或者如果你不需要访问该组件中的任何redux状态,则传递null。
  • 另外,你没有在你的调度中传递一个动作类型。它应该具有您似乎只有 {payload} 的格式 {type: actionType, payload}。

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


【解决方案1】:

首先在此处的第一个代码中

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

  export default connect(mapDispatchToProps) (Location1);

您需要将第一个参数传递给 connect ,即 mapStateToProps 但如果您不想使用它,请改为传递 null

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

你还可以通过传递 actionType(required) 和 actionPayload(optional) 在 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
              };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2023-01-11
    • 2020-06-14
    相关资源
    最近更新 更多