使用纯反应原生将状态数组从类传递到函数中 [英] Passing state array from class into function with pure react native
问题描述
我正在获取 rest api 并将其保存到 App 类 中的数组 jsonData 中,因为我实现了 react-navigation,我想在这个类之外显示它的内容,在函数.我多次阅读以使用 redux,但我完全是 React Native 初学者,我唯一需要使用 state 的是一个包含我需要显示的内容的数组.我没有做任何复杂的事情,所以我很困惑为什么将一个数组传递给一个函数如此困难.
I am fetching rest api and saving it into array jsonData in App class and because I implemented react-navigation, I want to display its content outside this class, in a function. I read multiple times to use redux, but I am complete react native beginner and the only thing I need to use state for is one array with things I need to display. I am not doing anything complicated so I am confused why is it so hard to pass one array to a function.
export default class App extends Component {
state = {
jsonData: [],
};
componentDidMount() {
fetch('https://pokeapi.co/api/v2/pokemon/ditto/', {
method: 'GET',
})
.then(response => response.json())
.then(json => {
this.setState({
jsonData: JSON.stringify(json),
});
})
.catch(error => {
console.error(error);
});
}
render() {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeScreen}/>
<Drawer.Screen name="Notifications" component={NotificationsScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}}
在这里我控制点击主屏幕后显示的内容,显然,我不能像我在这里那样打印它.我尝试在 stackoverflow 中搜索建议使用带有 props 的构造函数的答案,但这些解决方案对我不起作用.
Here I control what to show after clicking on Home screen, obviously, I cant print it like I do here. I tried searching stackoverflow with answers suggesting to use constructor with props, but these solutions did not work for me.
function HomeScreen() {
return (
<View>
<Text>this.state.jsonData</Text>
</View>
);
}
在不使用类似 redux 的库的情况下,我需要在代码中更改哪些内容才能将数组传递给 Homescreen 函数?
What do I need to change in my code to pass the array to the Homescreen function without using redux-like libraries?
推荐答案
你可以这样做:
render() {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={() => <HomeScreen data={this.state.jsonData}/>}/>
<Drawer.Screen name="Notifications" component={NotificationsScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}}
function HomeScreen({data}) {
return (
<View>
<Text>{JSON.stringify(data)}</Text>
</View>
);
}
这篇关于使用纯反应原生将状态数组从类传递到函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!