簡體   English   中英

如何在 React Native 中顯示來自 API 的數據而沒有錯誤未定義屬性?

[英]How to display data from API in React Native without error undefined property?

當我在顯示中使用 dataSource[0].first_name 時,總是出現未定義的屬性錯誤。

export default class Profile extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            dataSource: []
        }
    }
    async componentDidMount() {
        const response = await fetch('http://api url goes here /api/v1/getUserInfo/40', {
            method: 'GET',
            headers: {
                'authorization': 'token ' + global.storeToken,
            }
        })
            .then((response) => {
                return response;
            })
            .catch((error) => {
                alert('Error!' + error)
            })

        const json = await response.json();
        this.setState({
            isLoading: false,
            dataSource: [json],
        });
    }

    render() {
        const { dataSource } = this.state;

        return (
            <Container>
                <Header span style={styles.headerStyle}>
                    <Body style={{ justifyContent: "center" }}>
                        <Label style={styles.labelNickname}></Label>
                        <Label style={styles.labelUserID}> {dataSource[0].first_name}</Label>
                    </Body>
                </Header>
            </Container>
        );
    };
}

api 內容為:

{
    "id": 40,
    "email": "kk@gmail.com",
    "first_name": "Kagura",
    "last_name": "Kinomoto",
    "birth_date": "1990-01-01T00:00:00.000Z"
}

總是有錯誤。

TypeError: Cannot read property 'first_name' of undefined

This error is located at:
    in Profile (at SceneView.js:9)
    in SceneView (at StackViewLayout.tsx:898)
    in RCTView (at View.js:35)
    in View (at StackViewLayout.tsx:897)
   etc...

奇怪的是它昨天在所有控制台日志和東西之后工作。 我只是讓筆記本電腦休眠,當我今天再次嘗試運行它時,錯誤又回來了。

將此行更新為以下內容。

{dataSource && dataSource[0] && dataSource[0].first_name}

這將確保dataSource[0]不是undefined

原因是您的fetch請求是異步的,因此在收到響應之前dataSource[0]是未定義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM