我不知道如何使用异步调用和 promise 处理来传递结果变量
这是我使用过的代码:
import React from 'react';
import {result} from './run.js';
export default class Films extends React.Component {
constructor(props){
super(props)
this.state = { data: 'constructor' }
console.log('cons')
}
componentDidMount() {
this.setState(async (state, props) => {
const value = await result;
console.log(value);
console.log('didMount')
return {data:value}
});
}
render (){
return (
<div>
<center> <h1> Weekend Box Office </h1></center>
<div className = 'data'>
<h1>{this.state.data}</h1>
</div>
</div>
);
}
}
我在组件文件中导入了我的 promise 对象(结果)。我不知道为什么我的promise字符串没有渲染。
最佳答案
你需要使用componentDidMount
componentDidMount is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here
因此您需要在 componentDidMount 内调用您的请求,并且需要将结果设置为组件的状态,以便在回调内您将调用 setState
更新结果,即组件状态
关于javascript - 如何使用 React 组件中的请求 api 将字符串传递给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58367431/