Javascript 将函数传递、接收和使用到子组件中
我仍在学习ReactJS/React Native,我肯定我遇到了一件愚蠢的事情。我的情况是这样的:我希望在我的子组件中接收数据,并在模式中显示它。因此: 我有一个类似axios、API等的函数:Javascript 将函数传递、接收和使用到子组件中,javascript,reactjs,function,react-native,components,Javascript,Reactjs,Function,React Native,Components,我仍在学习ReactJS/React Native,我肯定我遇到了一件愚蠢的事情。我的情况是这样的:我希望在我的子组件中接收数据,并在模式中显示它。因此: 我有一个类似axios、API等的函数: getProductInfo = (product_id) => { axios.get( `API-EXAMPLE` ) .then((response) => { this.setState({ isVis
getProductInfo = (product_id) => {
axios.get(
`API-EXAMPLE`
)
.then((response) => {
this.setState({
isVisible: false,
productInfo: response.data
})
console.log(this.state.productInfo);
})
}
我使用onModalPress将函数传递给我的子组件:
<CatalogList productsList={this.state.displayProducts} onModalPress={this.getProductInfo}/>
一切正常,我在控制台中显示信息。log this.state.productInfo
我的问题和我认为很简单。。。这是我如何在console.log中存储/储存我的信息,以在我的模式中使用它,并像在本例中那样调用它:
<Modal isVisible={false}>
<View style={{ flex: 1 }}>
<Text>{productInfo.rewiew_wine_waiter}</Text>
</View>
</Modal>
当然,欢迎您提供任何其他建议
React是组件层次结构中的单向数据流
假设您有一个获取所有数据的容器组件:
class MyContainer extends Component{
state = {
myItensToDisplay: []
}
componentDidMount(){
//axios request
.then(res => this.setState({myItensToDisplay: res.itens}))
}
}
看起来不错!现在,所有要显示的数据都已提取并存储在容器的状态中。让我们将其传递给Itemcomponent:
class MyContainer extends Component{
// All the code from above
render(){
const itens = this.state.myDataToDisplay.map( item =>{
return(<Item name={item.name} price={item.price} />);
})
return(
<div>
{itens}
</div>
)
}
}
现在,您正在获取要在父组件中显示的所有数据,并通过道具将这些数据分发给它的子组件。您的console.log在哪里?您可以发布更多代码吗?您在哪里使用此模式?您可以将保存在您的状态中的productInfo作为道具传递给您的Modal。你对此有问题吗?我更新了代码。我把我的子组件的所有代码。这里有一个.map,我可以从中获取每种产品的信息,并返回p.id以通过我的函数。模态在这个代码中,所以当我浏览一个产品时,我可以得到我放在函数中的产品id,但只在控制台中显示它。我编辑了我的子组件的代码。我正在通过父组件中处于状态的productList进行.map。在这里,我可以在onModalPressp.id中获取产品标识,并将其显示在函数的console.log中。那我怎么能把它当作道具呢?我相信你看得不对。你有一个productList,这意味着你的父组件中有几个产品。现在,您必须将此列表中的每个产品作为一个组件来理解。因此,映射应该发生在父组件内部,并为列表中的每个元素返回单个产品组件。在父级中:const myProducts=this.state.productlist.mapproduct=>。然后在父对象中呈现{myProducts}
class MyContainer extends Component{
state = {
myItensToDisplay: []
}
componentDidMount(){
//axios request
.then(res => this.setState({myItensToDisplay: res.itens}))
}
}
class MyContainer extends Component{
// All the code from above
render(){
const itens = this.state.myDataToDisplay.map( item =>{
return(<Item name={item.name} price={item.price} />);
})
return(
<div>
{itens}
</div>
)
}
}