ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 오류 정의되지 않은 속성없이 React Native에서 API의 데이터를 표시하는 방법은 무엇입니까?
    카테고리 없음 2020. 8. 15. 14:19

    질문

    표시 할 때 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...

    이상한 점은 어제 모든 콘솔 로그와 항목 후에 작동했다는 것입니다. 노트북을 최대 절전 모드로 전환했을뿐 오늘 다시 실행하려고했을 때 오류가 다시 발생했습니다.


    답변1

    이 행을 다음으로 업데이트하십시오.

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

    이렇게하면 dataSource [0] undefined 가 아닙니다.

    그 이유는 fetch요청이 비동기식이므로 응답을받을 때까지 dataSource [0] 가 정의되지 않기 때문입니다.



     

     

     

     

    출처 : https://stackoverflow.com/questions/58606055/how-to-display-data-from-api-in-react-native-without-error-undefined-property

    댓글

Designed by Tistory.