【问题标题】:how to implement crud axios in react native using react native class component? (API)如何使用 react native 类组件在 react native 中实现 crud axios? (API)
【发布时间】:2021-06-16 08:12:55
【问题描述】:

谁能帮帮我,

我正在尝试使用 axios 与类组件反应原生的简单 CRUD, 将数据从 GET 传递到 Details 数据我成功了,但是在 DETAIL 页面上只检索一个数据时我遇到了问题, 当我尝试 console.log(dataTampung) / console.warn(dataTampung) 时,数据数组出现了,但我们想显示它而不是 undefined。

import React, { Component } from 'react'
import { Text, View } from 'react-native'
import axios from 'axios'

export class DetailData extends Component {

    constructor(props) {
        super(props)
        
        this.state = {
            dataTampung: []
        }
    }

    componentDidMount (){
        this.getData(); 
    }
    
    getData = () => {
        axios.get('http:my_local_ip_endpoind/api.php?on=detail&id='+this.props.route.params.id)
        .then( response => {
            this. setState({
                dataTampung:response.data.data.result
            })
        })
        .catch(function (error) {
            console.log(error);
        });
    }

    render() {
        const { id } = this.props.route.params;
        const { dataTampung } = this.state;

        console.warn(dataTampung);
        return (
            <View>
                <Text> This ID  = {id} </Text>
                <Text> Title  = {`${dataTampung.title}`} </Text>
            </View>
        )
    }
}

export default DetailData

这就是它的显示方式:enter image description here

请帮忙:( 我为我糟糕的英语提前道歉。

【问题讨论】:

    标签: react-native api axios


    【解决方案1】:

    您正在尝试使用点符号访问数组。首先,在 dataTampung[0] 中访问数组中的特定索引,这将为您提供对象,然后您可以访问标题为 dataTampung[0].title

    【讨论】:

    • 我认为还是一样,不工作,相反我得到一个错误 = ERROR TypeError: undefined is not an object (evaluating 'dataTampung[0].title')
    • 我认为您需要先检查数组是否有长度,然后再尝试访问它。
    • 是的,它的工作..当我尝试为数组 dataTampung 提供 if else 条件时.. 非常感谢.. :)
    猜你喜欢
    • 2016-09-22
    • 2017-02-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多