javascript - 如何在反应导出的网页上显示承诺的结果
问题描述
我读过的所有关于 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])
解决方案
所有 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 钩子的信息。
推荐阅读
- python - 用于真实数据的 python mathplotlib
- python - 发生异常:配置不当
- python - 在更改下拉列表中的选项时从 URL 未更改的站点中抓取数据
- r - 在 Shiny 中选择选项时删除滑块
- node.js - 使用单独的身份验证服务器时如何以编程方式刷新访问令牌 (JWT)?
- javascript - Reactjs 中的背景图像映射与 Material UI
- azure - cosmosDB RU 吞吐量是如何实施的
- c++ - 如何通过代理主机运行文件预览处理程序
- java - @在Java中做什么?
- python - 将多处理与使用 C++ 类作为基类的 python 对象一起使用时,__init__ 中缺少参数