programing

반응 기본 약속 값을 변수에 문자열로 전달

prostudy 2022. 3. 11. 22:46
반응형

반응 기본 약속 값을 변수에 문자열로 전달

나는 React Native를 처음 접한다.나는 약속을 만들어 대응 자료를 얻을 수 있어야 한다.

export async function findColor() {
    
        try{
            const token = await AsyncStorage.getItem('token');
            const id = await AsyncStorage.getItem('id');

            const resp = (
                await api(token).get(`api/blockgroup/getList`)
            ).data;
           
            const retVal = '"' + resp.data[0].template.mcolor +'"';
            
            console.log (typeof retVal, retVal, 'retvalue');
       
            return retVal;
        }
        catch(err){
            return {
                error: true,
                code: err.request.status,
            };
        }
    }

하지만 내가 그 기능에 전화를 걸었을 때 나는 이런 것을 얻었다.

{"_U": 0, "_V": 0, "_W": null, "_X": null}

을 사용하여 값에 액세스할 수 있다는 것을 알게 되었다..then()콘솔에 사용할 값을 인쇄하려고 할 때:

findColor().then(response => console.log(response));

문자열 값을 받았다.

"#0eade1"

그런데 그 값을 어떻게 변수에 문자열로 전달할 수 있는지 모르겠다.변수를 만들고 싶다고 가정해 봅시다.color그리고 그 가치를 넘기다."#0eade1"어떻게 해야 하지?

누가 나를 도와줄 수 있다면 정말 고마워.고마워!

편집: 나는 단지 이것을 분명히 하고 싶다.가져오기에서 다른 모듈로 전달해야 하기 때문에 문자열로만 전달하면 된다. 내가 전화한 후크의 값으로 테마 색상을 변경해야 하는 구성 모듈이 있다.이 구성은 문자열 개체만 허용하며, 구성 모듈에서 reactive native 구성 요소를 사용해야 하는지 모르겠다.

그걸 다룰 수 있는 고리를 만들 수 있을 겁니다.다음 조각들을 고려해보라.

export function useColor() {
    const [color, setColor] = useState()

    React.useEffect(() => {

        // you should add your function in here
        findColor().then(response => setColor(response))

    }, [])
    
    return {
        color,
    }
}

그런 다음 필요할 때마다 화면에 있는 후크를 사용하십시오.color.


const TestScreen = () => {

    // color can used however you like
    const {color} = useColor()
}

편집: 후크를 사용할 수 없는 클래스 구성요소를 사용하는 것으로 판단됨.우리는 여전히 똑같이 할 수 있다.

constructor(props) {
    ...
    this.state  =   {
       color : "",
    }
}
componentDidMount() {
    findColor().then(response => this.setState({color: response}))
}

render() {
   return <Text>this.state.color</Text>
}

이것을 사용해 봐야 정상 함수 호출로 사용할 수 있다.

export async function findColor() {
            const token = await AsyncStorage.getItem('token');
            const id = await AsyncStorage.getItem('id');
            api(token).get(`api/blockgroup/getList`)
            .then(resp=>{
              const retVal = '"' + resp.data[0].template.mcolor +'"';
            
              console.log (typeof retVal, retVal, 'retvalue');
       
              return retVal;
            });
            .catch((err){
            return {
                error: true,
                code: err.request.status,
            };
        })
    }

참조URL: https://stackoverflow.com/questions/71223818/react-native-promise-pass-the-value-to-variable-as-string

반응형