【问题标题】:React setState return undefined with function [duplicate]用函数反应setState返回未定义[重复]
【发布时间】:2019-04-13 23:46:09
【问题描述】:

在我的应用程序中,令牌用于通过函数检索用户数据。就是这样:

export function getUserInfos(token) {
    if (token == "") {
        window.location = "/";
    }
    axios.get(
        url,
        {
            headers: {
                "Authorization": "Bearer " + token
            }
        }
    ).then((result) => {
        var surname = result.data.userInfos.surname;
        var name = result.data.userInfos.name;
        var userInfos = {
            surname: surname,
            name: name
        }
        document.title = "Profil - " + surname + " " + name;
        console.log(userInfos)
        return userInfos;
    }).catch((err) => {
    })
}

console.log(userInfos) 在调用该函数时工作正常,但在我的组件一侧使用setState() 无法获取此值。无论我做什么,我仍然会收到undefined。这是我的组件中的代码:

class HomePage extends Component {
    static propTypes = {
        cookies: instanceOf(Cookies).isRequired
    };

    constructor(props) {
        super(props);

        const { cookies } = props;
        this.state = {
            token: cookies.get('token')
        }
    };
    componentDidMount() {
        this.setState((state, props) => {
            return {userInfos: getUserInfos(this.state.token)}
        }, () => {
            console.log(this.state.userInfos) // 'undefined'
        })
    }

    render() {
        console.log(this.state)
        return (
            <div>
                <h1>MyHomePage</h1>
            </div>
        )
    }
}

export default withCookies(HomePage);

我确定这是异步函数的问题,但我无法确定问题出在哪里或我做错了什么。我也查了一下,这不是我的函数getUserInfos的导入问题。

【问题讨论】:

  • 试试:async componentDidMount() { let user = await getUserInfos(this.state.token) this.setState({ userInfos: user }) }
  • 您的getUserInfos 函数在任何地方都没有return xyz(axios 回调函数之一有,但getUserInfos 没有)。所以称它为undefined。请参阅链接的问题,但简而言之:您需要:1.从getUserInfos返回承诺,2.删除getUserInfos中的错误抑制器并允许错误传播给调用者,3.使用它返回的承诺调用它,并且仅在承诺解决时设置状态(在它解决时设置userInfos,在它拒绝时设置显示错误条件)。
  • @SteveNosse - 只有当你有一个try/catch 时。 React 不会消耗使componentDidMount 产生的承诺,因此不会处理错误。
  • 我从未真正接触过 Promises,但它解决了我的问题。谢谢!

标签: javascript ajax reactjs token restful-authentication


【解决方案1】:

您需要以另一种方式在componentDidMount 中使用api 调用。仅在 promise 解决后设置状态。

componentDidMount() {
    getUserInfos(this.state.token).then((userInfos) => {
      this.setState({userInfos: userInfos})
    })
}

【讨论】:

  • getUserInfos 也需要编辑以返回承诺。此外,您可以将 {userInfos: userInfos} 替换为 {userInfos}。 (但这是一个经常被问到的副本,具有强大的 dupetarget。)
  • @T.J.Crowder 你可以使用任何语法 ES6 或 ES5。这只是一个语法,没关系。 getUserInfos 当前返回一个带有 return 的承诺。
  • 建议你再看一遍。它没有。 (而且由于您已经在使用 ES2015+ 语法,我只是想指出您可以让它更简洁。)
  • 好的,知道了。只需在axios调用前加上return即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 2015-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多