react-native - 将 Redux Store 连接到组件以使用标记填充 map

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

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

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

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

[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>
  );
};

./商店/ Action

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
    };
};

./存储/ 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
});

最佳答案

由于您的组件是一个无状态组件,您可以将plot props 直接从this.props 使用 mapStateToProps 绑定(bind)到商店的状态

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
 };

关于react-native - 将 Redux Store 连接到组件以使用标记填充 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52121354/

相关文章:

javascript - React.js Redux reducer 不插入项目

javascript - 尝试将 React 连接到 redux

React-native-maps LocalTile 存储图 block

javascript - 导航 startTabBasedApp 时 React Native Navigation 崩溃

react-native - 卸载 View 时防止状态丢失

javascript - 在哪里调用 AsyncStorage.getItem( ) 函数来加载react-native中保存的数据?

javascript - 在 React Native Redux 中调度导入的函数

android - 更改整个 React Native App 的语言

reactjs - 如何在React Native中导入组件过去的两个文件夹?

react-native - 如何从抽屉导航器菜单导航到特定选项卡 native react