如何在reactjs中创建异步设置状态?

问题描述 投票:0回答:1

有一个使用类的 ReactJS 项目,如下所示:

import { Component } from 'react';

class FooComponent extends Component {

    async setStateAsync(data) {
        return (new Promise(resolve => this.setState(data, resolve)));
    }

    async login() {
        // Preparing UI with loader
        return this.setStateAsync({
            sending: true,
            badCredentials: null
        })
        .then(AuthService.login(...))
        .then(...)
        .then(foo => this.setState({ foo: foo }))
        .then(...)
        .catch(e => this.setState({
            sending: false,
            badCredentials: e
        }))
    }
}

为什么不在同一个函数中使用两个

setState
?,reactJS在异步函数中保持上下文有问题,第一个设置状态改变html内容但是是异步的,但是函数不是异步的,需要完成回调,不能等待结果以内联模式继续,为了解决这个问题,我做了一个异步
setstate
,并且在同一函数中多次使用
asyncState
时工作正常。

我尝试将函数设置为全局函数到

Component
类,来自
index.js
:

import ReactDOM from 'react-dom/client';
import React, { Component } from 'react';
import reportWebVitals from './reportWebVitals';
import App from './app';

// Set a async state function
Component.prototype.setStateAsync = async (data) =>
    (new Promise(resolve => this.setState(data, resolve)));

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);

reportWebVitals();

但是不起作用,初始化

setState
类时找不到
Component
函数,
this
对象不是新类的实例。

如何访问已初始化类的当前

setState
实例或将异步函数设置为
Componen
的全局函数?

javascript reactjs asynchronous
1个回答
1
投票

非常好的主意,遗憾的是 ReactJS 没有基于 Promise 的异步函数来创建 Promise 链。

您的问题是基于 javascript 实现中的一个错误,该错误不允许在原型定义中使用 lambda 语法,要解决此问题,您必须将 lambda 函数样式更改为传统:

Component.prototype.setStateAsync = async function(data){
    return new Promise(resolve => this.setState(data, resolve));
}
© www.soinside.com 2019 - 2024. All rights reserved.