首页 > 解决方案 > 围绕 Promise 的问题

问题描述

我遇到了 Promises 待处理且未及时解决的问题。当我尝试使用异步等待一个值时,我最终得到“对象作为 React 子级无效(发现:[object Promise])。如果您打算渲染一组子级,请改用数组。 " 这可能是因为我正在调用这个我试图使用的特殊方法,它在渲染生命周期方法中返回一个承诺。好吧,我尝试使用 .then 来检索该值,但这也不起作用。

我将列出几个文件并尽我所能解释我能做什么,如果有更好的方法来做我想做的事情,建议会很棒!如果能修复就更好了!任何帮助是极大的赞赏!

App.js(主应用程序)组件 - Navigation.js(导航栏。) - MainContent.js(主要内容:一旦您单击导航项,主要内容内的所有内容都会更改)

MainContent.js

tabHandler = (tab) => {
//what do I do here? Immediately if I place the async keyword in the definition, the compiler hates me, but if I don't, then I don't get what I want.

    const test = this.props.tabAPICall(tab).then(value => { console.log(value) })
    console.log(test);

    //if(tab === all the different navigation tabs, render stuff differently){
    //as an example:
    // return <Songs />
    //}
    //else 
}

render(){
const { chosenTab } = this.props;

    return (
        <React.Fragment>


    <ul.className="main-content">
            {
                chosenTab !== "" ? this.tabHandler(chosenTab) : null
            }
        </ul>
    </React.Fragment>
)

}

tabAPICall 来自 App.js 这里:

tabAPICall = (tab) => {
    const { token, baseUrl } = this.state;

    fetch(`${baseUrl}/albums`, {
        method: 'GET',
        headers: { 'Authorization': 'Bearer ' + token }
    })
    .then((response) => response.json())
    .then((data) => {
        return data;
    })

selectedTab 在应用程序级别更新以触发重新渲染,这是我想要的

标签: javascriptreactjsapipromise

解决方案


您应该将从 API 获取的数据设置为您的组件状态。并在状态下显示数据:

在tabHandler中,我们拿到数据后,通过setState({ song: value })将其设置为this.state.song。当状态中的数据发生变化时。React 将进行重新渲染并将状态中的新数据注入您的组件。

constructor() {
   this.state = { song: null }
}

componentDidMount() {
    this.tabHandler(this.props.chosenTab)
}

componentWillReceiveProps(nextProps) {
    if (nextProps.chosenTab != this.props.chosenTab) {
        this.tabHandler(nextProps.chosenTab)
    }
}

tabHandler = (tab) => {
//what do I do here? Immediately if I place the async keyword in the definition, the compiler hates me, but if I don't, then I don't get what I want.

    this.props.tabAPICall(tab).then(value => { this.setState({ song: value }) })
}

render(){
    const { chosenTab } = this.props;

    return (
        <React.Fragment>


    <ul.className="main-content">
            { this.state.song ? <Song someProp={song} /> : null }
        </ul>
    </React.Fragment>
)

推荐阅读