gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:43:45 24 4
gpt4 key购买 nike

这是我的代码:

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]). 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. Check the render method of `SportPlayers`.

我想弄清楚为什么会显示此错误。 fetchSport 函数应该返回一个字符串(如 console.log 所建议的那样),但它似乎返回了一个 promise 到 View 。

下面是我的 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'
}
]
}
}

最佳答案

正如很多人已经说过的,async 函数将始终返回一个 Promise 对象,然后您可以使用 .then()< 获取其值.

一般来说,如果您需要向服务器发出很多请求,您应该使用状态管理框架,例如Redux。 .然而,Redux 引入了很多样板文件。如果您的用例很简单,您可以只使用 local UI state存储您的通话结果。

像这样:

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>
)
}
}

关于javascript - 异步等待和获取语法在 React 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43212124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com