【发布时间】:2020-10-16 18:52:01
【问题描述】:
父组件: 构造函数:
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: null,
show: false,
varFoodId: null,
};
}
这是我通过 API 请求获取数据的函数
fetchData = (item) => {
fetch(
`https://api.edamam.com/api/food-database/parser?ingr=${item}&app_id=${APP_ID}&app_key=${APP_KEY}`
)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
itemArray: responseJson.hints,
});
})
.catch((error) => {
console.log(error);
});
Keyboard.dismiss();
};
我按下按钮以获取数据并返回包含有关各个项目的信息的平面列表。都是可以触摸的。
<Button
title="Search"
onPress={() => this.fetchData(this.state.item)}
/>
<View style={styles.paddingForResultsContainer}>
<FlatList
style={styles.resultsBackground}
data={this.state.itemArray}
renderItem={({ item, index }) => (
<TouchableOpacity
onPress={() =>
this.setState({
show: true,
})
}
>
父组件底部的模态组件
<NewModal
showUs={this.state.show}
toggleShow={() => this.setState({ show: false })}
foodInfo={item}
></NewModal>
</TouchableOpacity>
)}
我的模态子组件:
const NewModal = (props) => {
return (
<Modal visible={props.showUs}/*visible={props.show} */>
<View style={styles.modalView}>
<View>
<Text>{props.foodInfo.food.nutrients.CHOCDF}</Text>
<Button title="props" onPress={() => console.log({props})} />
<Button title="Back" onPress={() => props.toggleShow()}></Button>
</View>
</View>
</Modal>
);
};
【问题讨论】:
-
您想在
onPress中运行fetchDataFlatList的TouchableOpacity对吗? -
我试过了,不幸的是我仍然得到相同的结果:/
-
fetchOnPressOpacity(){ this.setState({ show: true, }) this.fetchData(this.state.item) };
-
嗯,好吧,所以您的问题不在于获取数据,我认为问题在于您已将
this.state.show传递给所有NewModal组件,因此如果this.state.show为真,则所有模态都是可见,如果为假,则不可见。 -
我明白了,那么您打算如何解决这个问题?
标签: javascript ios reactjs react-native