首页 > 解决方案 > 如何在反应导出的网页上显示承诺的结果

问题描述

我读过的所有关于 Promise 的文章都显示了带有 console.log 的示例 - 我正在使用 AWS Athena,并希望在我的 React 导出的网页上显示结果。反应导出不允许使用 .then。所以我需要将承诺解析为外部变量。

client 是 aws athena 客户端,它返回我需要解决的承诺。

async function getResult(){
try {
    return await client.send(command);
  } catch (error) {
    return error.message;
  }
}

export default getResult()

我想在 App.js 中显示结果

render() 
{
return (
   { athena }
)

它显示在控制台中,但不显示在网页上,因为在解析变量之前加载了页面。

更完整的 App.js 示例

import athena from './athena';
class App extends Component {
render() 
  {
    let athena_result = athena.then(function(result) {
      console.log(result)
    }
    )

  return ( athena_result )

导致错误

Error: Objects are not valid as a React child (found: [object Promise])    

标签: javascriptreactjspromise

解决方案


所有 React 组件的render方法都被认为是一个纯粹的同步函数。换句话说,应该没有副作用,也没有异步逻辑。错误Error: Objects are not valid as a React child (found: [object Promise])是组件试图呈现 Promise 对象。

使用 React 组件生命周期来发布副作用。componentDidMount用于安装组件时的任何效果。

class App extends Component {
  state = {
    athena: null,
  }

  componentDidMount() {
    athena.then(result => this.setState({ athena: result }));
  }

  render() {
    const { athena } = this.state;
    return athena;
  }
}

如果您需要在组件安装后稍后发出副作用,那么componentDidUpdate是要使用的生命周期方法。

类组件仍然有效,并且没有计划在短期内移除它们,但功能组件确实是前进的方向。这是上面代码的示例函数组件版本。

const App = () => {
  const [athenaVal, setAthenaVAl] = React.useState(null);

  React.useEffect(() => {
    athena.then(result => setAthenaVAl(result));
  }, []); // <-- empty dependency array -> on mount/initial render only

  return athenaVal;
}

代码稍微简单一些。如果你愿意,你可以阅读更多关于React 钩子的信息。


推荐阅读