React Redux 承诺错误 - (...).then 不是一个函数

React Redux promise error - (...).then is not a function

在提供的问题中查看了这个,但 是最接近的,它并没有真正解决我的问题。

我有一个代码块(在页面下方有详细说明)作为更大的获取块的一部分。它到达此代码块并且如果此代码块被注释掉也可以正常运行,即它执行成功fetch etc 和 returns JWT 没问题但是...添加这个块我得到以下错误:

TypeError: (0 , _localStorageDropDowns.confirmSelectDataExistance)(...).then is not a function

指的是另一个文件夹中的这个函数(导入正确)..

export const confirmSelectDataExistance = () => {
  const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
  const statesJson = localStorage.getItem(STATES)
  const suburbLocationsJson = localStorage.getItem(LOCATIONS)
  if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
    console.log('something exists in localstorage')
    return true
  }
    console.log('nothing in localstorage')
  return false
}

简单函数 - returns 判断对错。

这是代码块 - 它在第一行失败:

    return confirmSelectDataExistance().then(isConfirmed => {
      if (!isConfirmed) {
        dispatch({ type: REQUEST_SELECT_DATA })
        console.log('gets here!', isConfirmed)
        const token = getJwt()
        const headers = new Headers({
          'Authorization': `Bearer ${token}`
        })
        const retrieveSelectData = fetch('/api/SelectData/SelectData', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
        })
          .then(handleErrors)
          .then(response => response.json())
          .then(selectData => {
            dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
            saveSelectData(selectData)
          });

        return saveSelectData(selectData);
      }
    })

根据我有限的经验,"confirmSelectDataExistance" 是一个函数,为什么说它不是?

最后,这里是完整的整个动作,因此您可以看到它是如何调用该块的。正如我所说的 - 注释掉该块,它可以完美地工作。

export const requestLoginToken = (username, password) =>
  (dispatch, getState) => {
    dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })

    const payload = {
      userName: username,
      password: password,
    }

    const task = fetch('/api/jwt', {
      method: 'POST',
      body: JSON.stringify(payload),
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
    })
      .then(handleErrors)
      .then(response => response.json())
      .then(data => {
        dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
        saveJwt(data)

        return confirmSelectDataExistance().then(isConfirmed => {
          if (!isConfirmed) {
            dispatch({ type: REQUEST_SELECT_DATA })
            console.log('gets here!', isConfirmed)
            const token = getJwt()
            const headers = new Headers({
              'Authorization': `Bearer ${token}`
            })
            const retrieveSelectData = fetch('/api/SelectData/SelectData', {
              method: 'GET',
              headers: {
                'Content-Type': 'application/json;charset=UTF-8'
              },
            })
              .then(handleErrors)
              .then(response => response.json())
              .then(selectData => {
                dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
                saveSelectData(selectData)
              });

            return saveSelectData(selectData);
          }
        })

      })
      .catch(error => {
        clearJwt()
        console.log('ERROR - LOGIN!',error)
      })
    addTask(task)
    return task
  }

编辑

经过几个小时的努力,我终于让这个工作起来了。这是完成的动作:

export const requestLoginToken = (username, password) =>
  (dispatch, getState) => {
    dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })

    const payload = {
      userName: username,
      password: password,
    }

    const task = fetch('/api/jwt', {
      method: 'POST',
      body: JSON.stringify(payload),
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
    })
      .then(handleErrors)
      .then(response => response.json())
      .then(data => {
        dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
        saveJwt(data)

        // Now check local storage for dropdown data..
        if (!confirmSelectDataExistance()) {
          dispatch({ type: REQUEST_SELECT_DATA })
          const token = JSON.stringify(data)
          const headers = new Headers({
            'Authorization': `Bearer ${token}`
          })
          const retrieveSelectData = fetch('/api/SelectData/SelectData', {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json;charset=UTF-8'
            },
          })
            .then(handleErrors)
            .then(response => response.json())
            .then(selectData => {
              dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
              saveSelectData(selectData)
            });

        }
      })

      .catch(error => {
        clearJwt()
        console.log('ERROR - LOGIN!', error)
      })
    addTask(task)
    return task
  }

这是它调用的函数:

export const confirmSelectDataExistance = () => {
  const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
  const statesJson = localStorage.getItem(STATES)
  const suburbLocationsJson = localStorage.getItem(LOCATIONS)
  if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
    console.log('something exists in localstorage')
    return true
  }
    console.log('nothing in localstorage')
  return false
}

与其他尝试不同的是,我使用 "data" 而不是调用 "getJwt()"。然后我使用了这条线:

const token = JSON.stringify(data)

获取刚刚得到的JWT

最后我用了@Karin 的答案,运行 也用了那个。 (由我点赞)

尝试这样的事情:

export const confirmSelectDataExistance = new Promise((resolve, reject) => {
  const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME);
  const statesJson = localStorage.getItem(STATES);
  const suburbLocationsJson = localStorage.getItem(LOCATIONS);
  if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
    console.log('something exists in localstorage');
    resolve(true);
  }
    console.log('nothing in localstorage');
  reject(false); // or resolve(false) if you want handle this situation inside then block also
});

错误不是说 confirmSelectDataExistance 不是函数,而是说 then 不是从它返回的函数,它是一个布尔值(它等同于到 false.then(...),这是行不通的)。

If 您似乎在尝试使用 then 作为条件。在那种情况下,一个简单的 if 语句应该可以工作:

if (confirmSelectDataExistance()) {
    // do things if it returns true
} else {
    // do things if it returns false
}
export const confirmSelectDataExistance = () => {

  return new Promise(function (resolve, reject) {

  const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
  const statesJson = localStorage.getItem(STATES)
  const suburbLocationsJson = localStorage.getItem(LOCATIONS)
  if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
    console.log('something exists in localstorage')
    resolve(true)
  }
  console.log('nothing in localstorage')
  reject(false)
 })
}