react-native - 使用纯反应原生将状态数组从类传递到函数
问题描述
我正在获取rest api并将其保存到App类中的数组jsonData中,并且因为我实现了react-navigation,所以我想在这个类之外的一个函数中显示它的内容。我多次阅读以使用 redux,但我完全是 react native 初学者,我唯一需要使用 state 的就是一个包含我需要显示的东西的数组。我没有做任何复杂的事情,所以我很困惑为什么将一个数组传递给一个函数这么难。
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,但这些解决方案对我不起作用。
function HomeScreen() {
return (
<View>
<Text>this.state.jsonData</Text>
</View>
);
}
在不使用类似 redux 的库的情况下,我需要在代码中进行哪些更改才能将数组传递给Homescreen函数?
解决方案
你可以这样做:
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>
);
}
推荐阅读
- html - 如何修复我所有的页脚链接不被混淆?
- gf - GF 中的关系从句 (which)
- typescript - 如何在 fp-ts 中使用管道删除 if 语句
- xml - 如何使用 eXist-db 将结果“拼接”成单个 XML 文档?
- c# - 虽然 String 是一种引用类型,但为什么“==”运算符在 2 个字符串中表现正确?
- reactjs - 由于 CORS,Spring 和 React websocket 聊天无法正常工作
- java - 错误需要权限 android.permission.CONNECTIVITY_INTERNAL android.permission.MAINLINE_NETWORK_STACK
- neo4j - 查询 Neo4j 的许多日期范围
- android - 在连续中断之前获取最后一个数组列表位置
- java - ZuulProxy 在 Spring Boot 应用程序中不起作用