简体   繁体   English

在componentDidMount()中调用函数的问题

[英]Problem with calling function in componentDidMount()

I am quite new in React.js and I have trouble with assigning my state through a static function call from another class. 我在React.js中是一个新手,在通过另一个类的静态函数调用分配状态时遇到麻烦。 This code: 这段代码:

componentDidMount() {
    this.setState(() => ({ movies: MovieService.getMovies() }));
}

Does not set my state. 不设置我的状态。 I believe the problem lies in my usage of the asynchronous function since if I use console.log(MovieService.getMovies()) , It shows Promise {<pending>} . 我相信问题出在异步函数的使用上,因为如果我使用console.log(MovieService.getMovies()) ,它将显示Promise {<pending>} However, I am still confused on how to fix this, thank you for the help! 但是,我仍然对如何解决此问题感到困惑,谢谢您的帮助!

componentDidMount() {
    MovieService.getMovies().then(moviesList => {
        this.setState({ movies: moviesList }));
    })
}

Assuming getMovies returns a list of movies, you need to wait for the promise it returns to fulfil and then assign the value to your state 假设getMovies返回了电影列表,则需要等待其返回的承诺完成,然后将值分配给您的州

Your code will be setting the movies field of your state to a Promise object representing the pending promise returned from the call to MovieService.getMovies() 您的代码会将您所在州的movies字段设置为Promise对象,该对象表示从对MovieService.getMovies()的调用返回的待处理的Promise

Try making the following adjustment to your code to resolve the issue, by first resolving the promise and then assigning the result to your components state: 尝试对代码进行以下调整以解决问题,方法是先解决Promise,然后将结果分配给组件状态:

componentDidMount() {

    MovieService.getMovies().then((movies) => {

        this.setState({ movies: movies });
    })
}

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

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