首页 > 解决方案 > 使用纯反应原生将状态数组从类传递到函数

问题描述

我正在获取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函数?

标签: react-native

解决方案


你可以这样做:

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>
    );
}

推荐阅读