【问题标题】:Response from Fetch() is undefined来自 Fetch() 的响应未定义
【发布时间】:2019-04-29 16:26:03
【问题描述】:

有两个文件:RegistrationScreen.jsapi.js

api.js 我正在运行fetch() 函数:

export const fetchAllUsers = () => {
    fetch(`http://${localIP}:${port}/api/userData`)
        .then(res => res.json()) 
        /* .then(json => console.warn('JSON: ' + json.userData[0].username))
        .catch(e => console.warn('ERROR: ' + e)) */
}

如果回复第二个.then(),我可以从回复中看到用户名

我正在将此函数导入 RegistrationScreen.js

import { fetchAllUsers } from '../../constants/api';

export default class RegistrationScreen extends Component{

    static defaultProps = {
        fetchAllUsers
    }

    onCreateButtonPress = async () => {
        ...
        let usernameValidation = await this.checkUsernameUniqueness();
        ...
    }

    checkUsernameUniqueness = async () => {
        const data = await this.props.fetchAllUsers();
        console.warn('user = ' + data)
    }
    ...

}

结果我进入了控制台user = undefined。 为什么我可以在 api.js 中看到数据,但在 RegistrationScreen.js 中看不到?

UPDATE_1

如果在 RegistrationScreen.js 中执行 console.warn(this.props.fetchAllUsers),我看到了函数代码,因此函数可见。

【问题讨论】:

  • 您是否从 fetch 函数返回响应?您可能想尝试在 then 中返回 res.json()。
  • 你需要return 承诺即export const fetchAllUsers = () => { return fetch(`http://${localIP}:${port}/api/userData`) ..... }

标签: javascript reactjs react-native fetch


【解决方案1】:

问题在于,当您调用fetchAllUsers 时,您不会从中返回任何内容,这就是您得到undefined 的原因。没有return 的函数返回未定义。

这将返回undefined

export const fetchAllUsers = () => {
    fetch(`http://${localIP}:${port}/api/userData`)
        .then(res => res.json()) 
        /* .then(json => console.warn('JSON: ' + json.userData[0].username))
        .catch(e => console.warn('ERROR: ' + e)) */
}

这会返回一个承诺

export const fetchAllUsers = () => {
    // added return 
    return fetch(`http://${localIP}:${port}/api/userData`)
        .then(res => res.json())
}

你忘记返回fetch的承诺

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 2019-12-30
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多