首页 > 解决方案 > 在 React Native 中使用类和渲染 api 调用

问题描述

我是 React Native 的新手,从 API 调用渲染数据时遇到问题。当我在函数内部执行此操作时,它在我使用 useEffect 时对我有用...但在类中我不能使用它。

这是我的代码示例...

export default class Categories extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            data: [],
            error: null,
        };
    }
    componentDidMount() {
        this.regionsGetRequest();
    }
    regionsGetRequest = () => {
        this.setState({ loading: true });

        const fetchData = async () => {
            const result = await axios(
                'https://...........json'
            );
            this.setState({
                data: result.data,
                error: result.error || null,
                loading: false,
            });

        };
        fetchData();
    };

    renderCategories = () => {
        const categoryLive = this.state.data;
        console.log(JSON.stringify(categoryLive));

我进入控制台:未定义,未定义...然后得到应有的结果...就像它出于某种原因运行了 3 次...如果我尝试将其放在 renderCategories 之上:

componentDidMount() {
        renderCategories();
    }

我只得到一个未定义的......当我连接变量 categoryLive 时,什么都没有加载。

对不起,我一直在努力解决这个问题......任何帮助都非常感谢!

无论我做什么,我总是接到 3 个电话……前两个空对象 [],第三个我得到了转储到控制台的真实结果。所以我的类别没有呈现......它们是空的。

这是更新的代码,我正在发布整个文件,它可能会敲响一些钟声。

export default class Categories extends React.Component {
    state = {
        myData: [],
    };
    componentDidMount() {
        axios
            .get('https://..............json')
            .then((res) => {
                const myData = res.data;
                this.setState({ myData });
            });
    }

    renderCategories = () => {
        const categoryLive = this.state.myData;
        console.log(JSON.stringify(categoryLive));

        const { navigation, route } = this.props;
        const tabId = route.params?.tabId;
        const categories = tabId
            ? categoryLive[tabId]
            : categoryLive.victoria_bc;
        //console.log(route.params?.tabId);
        return (
            <ScrollView
                showsVerticalScrollIndicator={false}
                contentContainerStyle={styles.categoryList}
            >
                <Block flex>
                    {categories.map((category) => (
                        <TouchableWithoutFeedback
                            key={`category-${category.id}`}
                            onPress={() => navigation.navigate('Category', { ...category })}
                        >
                            <Block flex card style={[styles.category, styles.shadow]}>
                                <ImageBackground
                                    source={{ uri: category.image }}
                                    style={[
                                        styles.imageBlock,
                                        { width: width - theme.SIZES.BASE * 2, height: 252 },
                                    ]}
                                    imageStyle={{
                                        width: width - theme.SIZES.BASE * 2,
                                        height: 252,
                                    }}
                                >
                                    <Block style={styles.categoryTitle}>
                                        <Text size={18} bold color={theme.COLORS.WHITE}>
                                            {category.title}
                                        </Text>
                                    </Block>
                                </ImageBackground>
                            </Block>
                        </TouchableWithoutFeedback>
                    ))}
                </Block>
            </ScrollView>
        );
    };

    render() {
        return (
            <Block flex center style={styles.categories}>
                {this.renderCategories()}
            </Block>
        );
    }
}

当我这样说时:我得到默认类别(所有数据都很好......)但我的导航不再工作......(route.params?.tabId 没有更新)

axios
    .get('https://.............json')
    .then((res) => {
        this.setState({
            myData: res.data,
                error: res.error || null,
                loading: false,
            });
            console.log('inside .then----' + JSON.stringify(this.state.myData));
            const { navigation, route } = this.props;
            const tabId = route.params?.tabId;
            const tmpCategories = tabId
                ? this.state.myData[tabId]
                : this.state.myData.victoria_bc;
            this.setState({ categories: tmpCategories });
            //console.log(route.params?.tabId);
        });

如果我把它像下面这样......类别对我来说是空的:

axios
    .get('https://.............json')
    .then((res) => {
        this.setState({
            myData: res.data,
                error: res.error || null,
                loading: false,
            });
            console.log('inside .then----' + JSON.stringify(this.state.myData));

        });
        const { navigation, route } = this.props;
        const tabId = route.params?.tabId;
        const tmpCategories = tabId
            ? this.state.myData[tabId]
            : this.state.myData.victoria_bc;
        this.setState({ categories: tmpCategories });
        //console.log(route.params?.tabId);    

对我有用的最终代码..

export default class Categories extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            myData: [],
            error: null,
        };
    }

    componentDidMount() {
        this.renderCategories();
    }

    renderCategories = () => {
        axios
            .get('https://.............json')
            .then((res) => {
                this.setState({
                    myData: res.data,
                    error: res.error || null,
                    loading: false,
                });
                //console.log('inside .then----' + JSON.stringify(this.state.myData));
            });
    };

    render() {
        if (this.state.loading) {
            return (
                <View
                    style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}
                >
                    <ActivityIndicator />
                </View>
            );
        } else {
            const { navigation, route } = this.props;
            const tabId = route.params?.tabId;
            const categories = tabId
                ? this.state.myData[tabId]
                : this.state.myData.victoria_bc;

            //console.log(route.params?.tabId);


            return (
                <Block flex center style={styles.categories}>
                    <ScrollView
                        showsVerticalScrollIndicator={false}
                        contentContainerStyle={styles.categoryList}
                    >
                        <Block flex>
                            {categories.map((category) => (
                                <TouchableWithoutFeedback
                                    key={`category-${category.id}`}
                                    onPress={() =>
                                        navigation.navigate('Category', { ...category })
                                    }
                                >
                                    <Block flex card style={[styles.category, styles.shadow]}>
                                        <ImageBackground
                                            source={{ uri: category.image }}
                                            style={[
                                                styles.imageBlock,
                                                { width: width - theme.SIZES.BASE * 2, height: 252 },
                                            ]}
                                            imageStyle={{
                                                width: width - theme.SIZES.BASE * 2,
                                                height: 252,
                                            }}
                                        >
                                            <Block style={styles.categoryTitle}>
                                                <Text size={18} bold color={theme.COLORS.WHITE}>
                                                    {category.title}
                                                </Text>
                                            </Block>
                                        </ImageBackground>
                                    </Block>
                                </TouchableWithoutFeedback>
                            ))}
                        </Block>
                    </ScrollView>
                </Block>
            );
        }
    }
}

标签: react-nativeaxios

解决方案


export default class Categories extends React.Component {
    constructor(props) {
    super(props);

    this.state = {
      loading: false,
      myData: [],
      error: null,
      categories: []
    };


  }

    componentDidMount() {
    renderCategories();
    }

    renderCategories = () => {
        this.setState({ loading: true });

         axios
        .get('https://..............json')
        .then((res) => {

            this.setState({ myData: res.data,
                            error: res.error || null,
                            loading: false 
            });
            const categoryLive = this.state.myData;
            console.log(JSON.stringify(categoryLive));
        });



    };

    render() {
       // Set params in your render method :


        const { navigation, route } = this.props;
        const tabId = route.params?.tabId;

        if (this.state.loading){
            return (
            <View style={{ flex : 1, alignItems:  'center', justifyContent:  'center' }}>
                <ActivityIndicator/>
                </View>

                );
            }   
        return (

  // assign in your return statement  
     this.setState({ categories: tabId
            ? categoryLive[tabId]
            : categoryLive.victoria_bc;})

        //console.log(route.params?.tabId);
            const { categories } = this.state.categories;
         <Block flex center style={styles.categories}>
            <ScrollView
                showsVerticalScrollIndicator={false}
                contentContainerStyle={styles.categoryList}
            >
                <Block flex>
                    {categories.map((category) => (
                        <TouchableWithoutFeedback
                            key={`category-${category.id}`}
                            onPress={() => navigation.navigate('Category', { ...category })}
                        >
                            <Block flex card style={[styles.category, styles.shadow]}>
                                <ImageBackground
                                    source={{ uri: category.image }}
                                    style={[
                                        styles.imageBlock,
                                        { width: width - theme.SIZES.BASE * 2, height: 252 },
                                    ]}
                                    imageStyle={{
                                        width: width - theme.SIZES.BASE * 2,
                                        height: 252,
                                    }}
                                >
                                    <Block style={styles.categoryTitle}>
                                        <Text size={18} bold color={theme.COLORS.WHITE}>
                                            {category.title}
                                        </Text>
                                    </Block>
                                </ImageBackground>
                            </Block>
                        </TouchableWithoutFeedback>
                    ))}
                </Block>
            </ScrollView>
        </Block>
        );
    }
}

推荐阅读