【问题标题】:Connecting Redux Store to Component to populate map with markers将 Redux Store 连接到组件以使用标记填充地图
【发布时间】:2018-08-31 18:59:11
【问题描述】:

简而言之,我正在尝试学习如何使用 redux。正如标题所示,我正在尝试将 redux 存储连接到组件,以便它可以使用标记(我在服务器上获取的)填充地图。

我知道我在加载 componentWillMount() 时已经连接了它。但是这样做会返回一个对象数组,这不是我真正想要的。

我不知道我说的是否正确,但我该如何让它返回一个状态/道具,我可以在我的 ./Component 中使用它来填充地图上的标记?

[EDIT1:我已按照 Pritish 的建议包含更改]

提前致谢。

./屏幕

class FindOnMapScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      userLocation: null,
      plots: []
    };
  }

  getUserLocationHandler = () => {
    navigator.geolocation.getCurrentPosition(position => {
      this.setState({
        userLocation: {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          latitudeDelta: 0.0622,
          longitudeDelta: 0.0421,
        }
      });
    }, err => console.log(err));
  };

componentDidMount() {
  this.props.onLoadPlacesToMap();
}

  render() {
    console.warn("props", this.props)
    return  (
      <View style={styles.container}>
        <FetchLocation onGetLocation={this.getUserLocationHandler} />
        <UsersMap 
          userLocation={this.state.userLocation}
          props={this.props.plots}
        />
      </View>
      )
    }
  };


const mapStateToProps = state => {
  return {
    plots: state.mapPlaces.plots
  };
};

const mapDispatchToProps = dispatch => {
  return {
      onLoadPlacesToMap: () => dispatch(getPlacesOnMap())
  };
};

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

./组件

const usersMap = props => {
let userLocationMarker = null;

if (props.userLocation) {
    userLocationMarker = <MapView.Marker coordinate={props.userLocation} />;
}

const plots = props.plots.map(plots => //.. tried to access here
    <MapView.Marker 
        coordinate={plots} 
        key={plots.id}
    />
);

return (
    <View style={styles.mapContainer}>
        <MapView 
            initialRegion={{
                latitude: 37.78825,
                longitude: -122.4324,
                latitudeDelta: 0.0622,
                longitudeDelta: 0.0421,
            }}
            region={props.userLocation}
            style={styles.map}
        >
            {userLocationMarker}
        </MapView>
    </View>
  );
};

./Store/Actions

export const getPlacesOnMap = () => {
return dispatch => {
    dispatch(authGetToken())
        .then(token => {
            return fetch("myAppURL/file.json?auth=" + token);
        })
        .catch(() => {
            alert("No valid token found!");
        })
        .then(res => {
            if (res.ok) {
                return res.json();
            } else {
                throw(new Error());
            }
        })
        .then(parsedRes => {
            const plots = [];
            for (let key in parsedRes) {
                plots.push({
                    latitude: parsedRes[key].location.latitude,
                    longitude: parsedRes[key].location.longitude,
                    id: key
                  });
                } console.log(plots)
                dispatch(mapPlaces(plots));
              })
        .catch(err => {
            alert("Oops! Something went wrong, sorry! :/");
            console.log(err);
        });
    };
};

export const mapPlaces = plots => {
    return {
        type: MAP_PLACES,
        plots: plots
    };
};

./Store/Reducer

const initialState ={
    plots: []
};

const reducer = (state = initialState, action) => {
    switch (action.type) {
      case MAP_PLACES:
        return {
            ...state,
            places: action.plots
        };
        default:
            return state;
    }
};

./ConfigureStore

const rootReducer = combineReducers({
    mapPlaces: mapPlacesReducer
});

【问题讨论】:

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


    【解决方案1】:

    由于您的 组件 是一个 无状态 组件,因此您可以将 plot props 直接从绑定的 this.props 传递给它使用mapStateToProps商店的状态

    componentDidMount {
      this.props.onLoadPlacesToMap() // ... Call your prop bound dispatcher func here
    }
    
    <UsersMap 
       userLocation={this.state.userLocation} 
       plots={this.props.plots}
    />
    

    在您的 Component 中,您可以通过 props.plots

    访问它们

    在您的 reducer 中,您需要将 places 更改为 plots 或在您的父类中类似地映射和映射它们。

    case MAP_PLACES:
       return {
         ...state,
         plots: action.plots
     };
    

    【讨论】:

    • 感谢@pritsh 的建议。可悲的是,我认为您正确组合我的减速器可能是对的。因为当我包含您的建议时,地图没有任何反应啊哈。我要看看它并找出原因。但与此同时,我已经更新了上面的代码以包含 combineReducers。
    • 您需要将places 替换为plots,因为在您的mapStateToProps 中,您要的是plots: state.mapPlaces.plots
    • 哈哈哈我怎么错过了。谢谢@Pritish!
    猜你喜欢
    • 2020-05-05
    • 2017-12-17
    • 2019-12-26
    • 2021-09-21
    • 2017-06-03
    • 2021-02-03
    • 2014-06-01
    • 2014-03-23
    • 2014-02-28
    相关资源
    最近更新 更多