更新另一个文件的值

时间:2019-11-07 14:25:59

标签: javascript react-native

我正在构建一个本机应用程序,我需要为每种用户类型更改主题颜色。我正在从服务器提取此颜色代码,并保持异步存储。

我尝试过添加func来更改原色变量,但是没有等待就将它们传递给我的代码给我保证没有价值

TheTypeOfParameter parameterFound = null;
TheTypeOfParameter parameterHavingDateNotNull = null;
TheTypeOfParameter parameterHavingDateNull = null;

bool foundDateNull = false;
bool foundDateNotNull = false;

foreach ( var item in query )
{
  if ( !foundDateNull && item.EndDate == null )
  {
    parameterHavingDateNull = item;
    foundDateNull = true;
  }
  else
  if ( !foundDateNotNull && item.EndDate > givenDate )
    foundDateNotNull = true;
  if ( !foundDateNotNull )
    parameterHavingDateNotNull = item;
  if ( foundDateNotNull || foundDateNull )
    break;
}

parameterFound = parameterHavingDateNotNull != null
               ? parameterHavingDateNotNull
               : parameterHavingDateNull;

原始:

import { AsyncStorage } from 'react-native';

let primaryColor = "orange"

const func = async () => {
    let some;
    let thing = await AsyncStorage.getItem("profile")
    thing = JSON.parse(thing)
    console.warn("thing", thing.background)
    if (thing.background != undefined) {
        some = thing.background
    } else if (thing == undefined) {
        some = "red"
    }
    return some
}

primaryColor = func()

2 个答案:

答案 0 :(得分:1)

您的函数是异步的。通过异步操作获取值。

示例

async componentDidMount(){

  primaryColor = await func() 
}

答案 1 :(得分:0)

从函数中获取解析的结果,然后将其设置为“ primaryColor”

func()

.then(color => primaryColor = color);

发现可能存在的任何错误。

.catch((e) => console.error(e))

或者如果您在异步函数中使用它,则只需

try {
    primaryColor = await func();
} catch(e) {
    console.error(e)
}