通过状态时无法读取未定义的属性“ map”并将其映射为道具

时间:2019-01-11 11:50:59

标签: react-native expo

我正在尝试将状态从App.js组件传递给Home.js中存在的ShopsMap组件,这是传递的代码

render() {
    const { shops, region } = this.state;
    return (
      <SafeAreaView>
        <ShopsMap shops={shops} region={region} />
      </SafeAreaView>
    );
  }
}

在Home.js中,我具有这种结构,其中具有ShopsMap和ShopsDetails组件,并且我尝试在这两个组件之间进行导航,如以下代码所示:

class ShopsMap extends Component {
  renderMarkers() {
    return this.props.shops.map((marker, i) => (
      <Marker key={i} title={marker.name} coordinate={marker.coords} >
      <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </Marker>
    ));
  }
  componentDidMount() { }

  render() {
    const region = this.props.region;
    return (
      <MapView
        region={region}
        showsUserLocation
        showsMyLocationButton
      >
        {this.renderMarkers()}
      </MapView>
    );
  }
}

class ShopsDetails extends Component {
  render() {
    return (
      <View>
        <Text>Details Screen</Text>
        <Button
          title="Go to Map"
          onPress={() => this.props.navigation.navigate('Map')}
        />
      </View>
    );
  }
}

const RootStack = createStackNavigator(
  {
    Map: {
      screen: ShopsMap,
    },
    Details: {
      screen: ShopsDetails,
    },
  },
  {
    initialRouteName: 'Map',
  }
);

const AppContainer = createAppContainer(RootStack);

export default class Home extends Component {
  render() {
    return <AppContainer />;
  }
}

我收到此错误,无法读取未定义的属性“ map” 当我在Home.js中只有ShopsMap并直接导出此类时,一切正常,但是当更改结构以在组件之间导航时,出现此错误

2 个答案:

答案 0 :(得分:0)

请参阅this page,以获取如何将参数传递到屏幕

答案 1 :(得分:0)

有两个想法:

1-在家庭班级中,尝试:

return <AppContainer {...this.props} />


2-在父组件中,尝试按以下方式传递道具:

<ShopsMap shops={this.state.shops} region={this.state.region} />