我正在尝试在我的本机应用程序中实现redux。
一切正常,但是当我更改数组名称时,应用程序无法呈现列表。
在App扩展类中,我有:
placeAddedHandler = placeName => {
this.props.onAddPlace(placeName);
};
render() {
return (
<View style={styles.container}>
<PlaceDetail
selectedPlace={this.props.selectedPlace}
onItemDeleted={this.placeDeletedHandler}
onModalClosed={this.modalClosedHandler}
/>
<PlaceInput
onPlaceAdded={this.placeAddedHandler} />
<PlaceList
places={this.props.places}
onItemSelected={this.placeSelectedHandler}
/>
</View>
);
}
在placesRed.js中
const initialState = {
places: [],
selectedPlace: null
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case ADD_PLACE:
return {
...state,
places: state.places.concat({
key: Math.random(),
name: action.placeName,
image: {
uri:
"https://www.randomImage.jpg"
}
})
};
现在,如果我将地点从initialState更改为placesList,则应用无法呈现。
在调试器中,我们可以在Placelist.js中看到:
const placeList = props => {
return (
<FlatList
style={styles.listContainer}
data={props.places}
renderItem={(info) => (
<ListItem
placeName={info.item.name}
placeImage={info.item.image}
onItemPressed={() => props.onItemSelected(info.item.key)}
/>
)}
/>
);
};
data = {props.places}->此处props也具有我的价值和位置,但具有不同的名称示例:props.placesList我仍然在props中具有值,但是placeList是“未定义”
我当然可以在我的应用中的任何地方将名称更改为placeList
有什么问题吗?如何解决?如果您想从我的应用中获取更多代码,请告诉我。
更改后:
PlaceList.js
const placeList = props => {
return (
<FlatList
style={styles.listContainer}
data={props.placesList}
renderItem={(info) => (
<ListItem
placeName={info.item.name}
placeImage={info.item.image}
onItemPressed={() => props.onItemSelected(info.item.key)}
/>
)}
/>
);
};
placesRed.js
const initialState = {
placesList: [],
selectedPlace: null
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case ADD_PLACE:
return {
...state,
placesList: state.placesList.concat({
key: Math.random(),
name: action.placeName,
image: {
uri:
"https://www.randomImage.jpg"
}
})
};
App.js
render() {
return (
<View style={styles.container}>
<PlaceDetail
selectedPlace={this.props.selectedPlace}
onItemDeleted={this.placeDeletedHandler}
onModalClosed={this.modalClosedHandler}
/>
<PlaceInput
onPlaceAdded={this.placeAddedHandler} />
<PlaceList
places={this.props.placesList}
onItemSelected={this.placeSelectedHandler}
/>
</View>
);
}
}
data = {props.placesList} ->该道具具有我的价值,但是placesList未定义
答案 0 :(得分:0)
在您的 App.js 中,您需要将道具传递到placesList
到您的 PlacesList 组件
<PlaceList
places={this.props.placesList} // <== replace places with placesList
onItemSelected={this.placeSelectedHandler}
/>