简体   繁体   English

异步等待和获取语法在React中不起作用

[英]Async await and fetch syntax not working in React

Here is my code: 这是我的代码:

export class App extends Component {
    constructor(props) {
        super(props)
    }
    async fetchSport(sport) {
        let headers = new Headers()
        headers.append('key-goes-here', 'pass-goes-here')
        headers.append('Accept', 'application/json')
        let request = new Request('api-url-goes-here' + sport, {headers: headers})
        let data = await fetch(request).then(response => response.json()).then(json => json.players.forward)
        console.log(data) // 'Christopher Brown'
        return data
    }
    render() {
        return (
            <div className='app'>
                <SportPlayers
                    sport={this.fetchSport('soccer')}
                />
            </div>
        )
    }
}

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). 未捕获的错误:对象作为React子对象无效(找到:[object Promise])。 If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. 如果您打算渲染孩子的集合,请改用数组或使用React附加组件中的createFragment(object)包装对象。 Check the render method of `SportPlayers`. 检查`SportPlayers`的渲染方法。

I am trying to figure out why this error is showing. 我试图弄清楚为什么显示此错误。 The fetchSport function should be returning a string (like console.log suggests), but it seems like a promise is returned to the view instead. fetchSport函数应该返回一个字符串(如console.log所建议的),但是似乎fetchSport返回了一个fetchSport

Bellow is my webpack.config.js: 波纹管是我的webpack.config.js:

var webpack = require("webpack");

module.exports = {
    entry: ["babel-polyfill", "./src/index.js"],
    output: {
        path: "/dist/assets",
        filename: "bundle.js",
        publicPath: "assets"
    },
    devServer: {
        inline: true,
        contentBase: "./dist",
        port: 3000 
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /(node_modules)/,
                loader: ["babel-loader", 'babel-loader?presets[]=es2016,presets[]=stage-3,presets[]=react'],
            },
            {
                test:  /\.json$/,
                exclude: /(node_modules)/,
                loader: ["json-loader"]
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader!autoprefixer-loader'
            },
            {
                test: /\.scss$/,
                loader: 'style-loader!css-loader!autoprefixer-loader!sass-loader'
            }
        ]
    }
}

As many people have said already, an async function will always return a Promise object, whose value you can then obtain by using .then() . 正如许多人已经说过的那样, async函数将始终返回Promise对象,然后可以使用.then()获取其值。

In general, if you need to make many requests to a server, you should be using a state management framework such as Redux . 通常,如果需要向服务器发出许多请求,则应该使用状态管理框架,例如Redux However, Redux introduces a lot of boilerplate. 但是,Redux引入了许多样板。 If your usecase is simple, you could just use local UI state to store the result of your call. 如果用例很简单,则可以仅使用本地UI状态来存储调用结果。

Something like this: 像这样:

export class App extends Component {
    constructor(props) {
      super(props)
      this.state = { sport: '' }
    }

    componentDidMount() {
      this.fetchSport('soccer').then(sport => this.setState({ sport }))
    }

    async fetchSport(sport) {
        let headers = new Headers()
        headers.append('key-goes-here', 'pass-goes-here')
        headers.append('Accept', 'application/json')
        let request = new Request('api-url-goes-here' + sport, {headers: headers})
        let data = await fetch(request).then(response => response.json()).then(json => json.players.forward)
        console.log(data) // 'Christopher Brown'
        return data
    }

    render() {
        return (
            <div className='app'>
                <SportPlayers
                    sport={this.state.sport}
                />
            </div>
        )
    }
}

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

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