通常,我尝试在组件加载时(在initialiseSellerData()中)加载一些数据,但我只想执行一次,即,如果刷新页面,则不会再次执行。请参阅下面的尝试和下面的特定问题的说明
class Index extends React.Component {
constructor(props) {
super(props);
this.state = {
initialised: false
};
}
componentDidMount = () =>
{
this.initialised()
if(this.state.initialised == false)
{
this.initialiseSellerData();
}
}
initialiseSellerData = async () =>
{
// this function makes a call to contract to initialise data
}
initialised = async () =>
{
const {sellContract } = this.props
const response = await sellContract.methods.initialised().call()
if(response == true)
{
this.setState({initialised: true})
}
}
我遇到的问题是在componentDidMount中,initialized()函数被正确调用,并且初始化状态被设置为true,但是当我对初始化进行检查时,它返回false(应该返回true)。为什么我的状态不持久/在函数调用之间传递。
答案 0 :(得分:0)
我认为您忘记使用await
。 initialised
是一个异步函数。因此调用函数应使用await
或then
来处理诺言。
componentDidMount = async () =>
{
await this.initialised()
}
initialiseSellerData = async () =>
{
// this function makes a call to contract to initialise data
}
initialised = async () =>
{
const {sellContract } = this.props
const response = await sellContract.methods.initialised().call()
if(response == true)
{
await initialiseSellerData();
this.setState({initialised: true});
}
}