繁体   English   中英

如何在js中通过return function()传递函数变量

[英]how to pass function variable by return function() in js

我曾与本机反应,我有一个问题......

const SignIn = () => {
    screensplash()
    fetch('http://api.megamouj.ir/api/v1/logincheck/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username,
        password: password
      })
    })
      .then((response) => response.json())
      .then((responseJson) => {
        login(responseJson.token).then(
          (token) => {
            setToken(token)

            getMoviesFromApiAsync()
          }
      
        )
      })
  }

当程序继续时

login(responseJson.token)

我遇到了这个错误:

Possible Unhandled Promise Rejection (id: 0): TypeError: Cannot read property 'then' of undefined

这是我的login()函数:

  const login = (token) => {
    setLoading(true)

    AsyncStorage.setItem('token', token, (error) => {
      if (token == 'wrong') {
        setIsLoggedIn(false)
        setLoading(false)
        ToastAndroid.show(
          'error',
          ToastAndroid.SHORT
        )
      } else if (!error) {
        setIsLoggedIn(true)
        setLoading(false)
      }
    })
    return token   }

请帮帮我!

您可以使用async / await处理从AsyncStorage.setItem返回的承诺并返回包含token的承诺:

const login = async (token) => {
  setLoading(true)

  await AsyncStorage.setItem('token', token, (error) => {
    if (token == 'wrong') {
      setIsLoggedIn(false)
      setLoading(false)
      ToastAndroid.show(
        'error',
        ToastAndroid.SHORT
      )
    } else if (!error) {
      setIsLoggedIn(true)
      setLoading(false)
    }
  })
  return token
}

似乎您甚至没有修改token 退货没有意义。 您可以使用responseJson.token代替:

const SignIn = () => {
  screensplash()
  fetch('http://api.megamouj.ir/api/v1/logincheck/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: username,
      password: password
    })
  })
    .then((response) => response.json())
    .then((responseJson) => login(responseJson.token))
    .then(() => {
      setToken(responseJson.token)

      getMoviesFromApiAsync()
    })
}

const login = async (token) => {
  setLoading(true)

  await AsyncStorage.setItem('token', token, (error) => {
    if (token == 'wrong') {
      setIsLoggedIn(false)
      setLoading(false)
      ToastAndroid.show(
        'error',
        ToastAndroid.SHORT
      )
    } else if (!error) {
      setIsLoggedIn(true)
      setLoading(false)
    }
  })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM