잡동사니

반응형

질문

 

example.js

import React from "react";
import { getInfo } from '../../actions/stuff'


class example extends React.Component {
  state = {


  }


  constructor(props) {
    super(props);
    const values = getInfo("123")



  }

stuff.js

export const getInfo = (id) => {
    const url = `/profile/${id}`;

    fetch(url)
        .then(res => {
            if (res.status === 200) {
                return res.json();
            }
        })
        .then(json => {
            if (json) {

                return json



            }

        })
        .catch(error => {
            console.log(error);
        });

}

우편 배달부에서는 {firstName : something, lastName : something, age : something}에 대해 3 개의 값을 가진 json을 반환합니다. json을 반환하고 싶지만 "const values = getInfo ("123 ")"는 정의되지 않습니다. getInfo 함수에서 console.log (json)이면 원하는 값을 제공하므로 내가 뭘 잘못하고 있는지 알 수 없습니다.

 

답변1

 

Promise은 가치를 즉시 해결하지 못할 수 있으므로, 가치를 얻는 유일한 확실한 방법은 가치를 기다리는 것입니다.

이것은 Promise에 따라 .then () 을 계속 연결하거나 ( .then () 은 일단 값이 해결되면 순서대로 실행 됨) 또는 사용하여 수행 할 수 있습니다 값이 해결되면 호출되는 콜백 함수 (여전히 .then () 를 사용하지만 함수에 의해 난독 화됨)

Promise을 계속 사용하십시오.

export const getInfo = (id) => {
    const url = `/profile/${id}`;

    return fetch(url)
        .then(res => {
            if (res.status === 200) {
                return res.json();
            }
        })
        .then(json => {
            if (json) {

                return json



            }

        })
        .catch(error => {
            console.log(error);
        });

}

getInfo('123').then(data => console.log(data));

다음 콜백 함수를 사용하십시오.

export const getInfo = (id, callback) => {
    const url = `/profile/${id}`;

    fetch(url)
        .then(res => {
            if (res.status === 200) {
                return res.json();
            }
        })
        .then(json => {
            if (json) {

                callback(json);



            }

        })
        .catch(error => {
            console.log(error);
        });

}

getInfo('123', data => console.log(data))

반응 component를 마운트 할 때이를 사용하려면 다음과 같은 작업을 수행 할 수 있습니다.

class example extends React.Component {
    componentDidMount(props) {
        getInfo('123').then(data => this.setState({ data }))
    }
}

 

 

 

 

 

출처 : https://stackoverflow.com/questions/63276433/how-do-i-return-something-from-a-function-call-to-constructor-i-e

반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band