gpt4 book ai didi

javascript - 如何将异步状态获取发送到组件?

转载 作者:行者123 更新时间:2023-11-30 14:53:52 25 4
gpt4 key购买 nike

我目前正在开发一个有趣的小应用程序。我在使用 axios 并将响应作为更新状态返回到我的 App 组件时遇到了问题。

然后我尝试允许另一个组件使用该状态,但我无法实际访问数据。我可以从 List 组件中使用 console.log(props),但我不确定如何输出实际数据,因为我只能输出 promise 结果。我希望能够输出 props.currentUser 并将其作为 googleId(使用 google Oauth2.0)。我确信解决方案很简单,但是,这是我的代码:

App.js ->

import React from 'react';
import helpers from '../helpers';
import List from './List';

class App extends React.Component{

state = {
currentUser: null
}

componentDidMount() {
this.setState(prevState => ({
currentUser: helpers.fetchUser()
}));
}

render() {
return (
<div>
<List currentUser={this.state.currentUser}/>
</div>
);
}
};

export default App;

helpers.js ->

import axios from 'axios';

var helpers = {
fetchUser: async () => {
const user = await axios.get('/api/current_user');

return user.data;
}
};

export default helpers;

列表组件 ->

import React from 'react';

const List = (props) => {

const renderContent = () => {
console.log(props);
return <li>{props.currentUser}</li>
}

renderContent();

return (
<div>
<h1>Grocery List</h1>
<ul>

</ul>
</div>
);
}

export default List;

输出->

{currentUser: null}
{currentUser: Promise}
currentUser: Promise__proto__: Promise[[PromiseStatus]]: "resolved"

最佳答案

因为 fetchUser 是一个 async function ,它返回一个 promise 。因此,在 App 组件中,您必须在该 promise 的 .then 中调用 setState,如下所示:

componentDidMount() {
helpers.fetchUser()
.then(data => {
this.setState(prevState => ({
currentUser: data
}));
});
}

关于javascript - 如何将异步状态获取发送到组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687290/

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