React native 在React Native中使用类和呈现api调用

React native 在React Native中使用类和呈现api调用,react-native,axios,React Native,Axios,我是React Native的新手,从API调用呈现数据时遇到问题。当我在函数内部执行它时,当我使用useEffect时,它对我有效。。。但是在课堂上我不能用这个 下面是我的代码示例 export default class Categories extends React.Component { constructor(props) { super(props); this.state = { loading: false,

我是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次。。。如果我尝试将以上渲染类别:

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>
        );
    }
}
如果我这样说的话。。。类别对我来说是空的:

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.Component{
建造师(道具){
超级(道具);
此.state={
加载:对,
myData:[],
错误:null,
};
}
componentDidMount(){
这个.renderCategories();
}
渲染类别=()=>{
axios
.get('https://.............json')
。然后((res)=>{
这是我的国家({
myData:res.data,
错误:res.error | | null,
加载:false,
});
//log('inside.then---'+JSON.stringify(this.state.myData));
});
};
render(){
if(this.state.loading){
返回(
);
}否则{
const{navigation,route}=this.props;
const tabId=route.params?.tabId;
const categories=tabId
?this.state.myData[tabId]
:this.state.myData.victoria_bc;
//控制台日志(route.params?.tabId);
返回(
{categories.map((categority)=>(
导航('Category',{…Category})
}
>
{category.title}
))}
);
}
}
}
导出默认类类别扩展React.Component{
建造师(道具){
超级(道具);
此.state={
加载:false,
myData:[],
错误:null,
类别:[]
};
}
componentDidMount(){
renderCategories();
}
渲染类别=()=>{
this.setState({loading:true});
axios
.get('https://..............json')
。然后((res)=>{
this.setState({myData:res.data,
错误:res.error | | null,
加载:错误
});
const categoryLive=this.state.myData;
log(JSON.stringify(categoryLive));
});
};
render(){
//在渲染方法中设置参数:
const{navigation,route}=this.props;
const tabId=route.params?.tabId;
if(this.state.loading){
返回(
);
}   
返回(
//在返回语句中赋值
this.setState({categories:tabId
?categoryLive[表ID]
:categoryLive.victoria_bc;})
//控制台日志(route.params?.tabId);
const{categories}=this.state.categories;
{categories.map((categority)=>(
导航('Category',{…Category})
>
{category.title}
))}
);
}
}
导出默认类类别扩展React.Component{
建造师(道具){
超级(道具);
此.state={
加载:false,
myData:[],
错误:null,
类别:[]
};
}
componentDidMount(){
renderCategories();
}
渲染类别=()=>{
this.setState({loading:true});
axios
.get('https://..............json')
。然后((res)=>{
this.setState({myData:res.data,
错误:res.error | | null,
加载:错误
});
const categoryLive=this.state.myData;
log(JSON.stringify(categoryLive));
});
};
render(){
//在渲染方法中设置参数:
const{navigation,route}=this.props;
const tabId=route.params?.tabId;
if(this.state.loading){
返回(
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>
            );
        }
    }
}
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>
        );
    }
}