这是 React 和 Axios 承诺使用正确吗?

Is this React and Axios then promise usage correct?

我在 React 项目中使用 axios,我想知道在这种情况下 then promise 的用法是否正确。
基本上,我使用 axios 在组件呈现时从数据库中获取数据。

class Participants extends React.Component{
    constructor(props){
        super(props);

        this.state = {
            databaseUsers: [],
        }

        this.getUsers = this.getUsers.bind(this);

    }

    getUsers(){
        var users = axios.get('/users/get-users').then((response) => {
            this.setState({databaseUsers: response.data});
        });
    }

    componentWillMount(){
        this.getUsers();
    }

    render(){
        console.log(this.state.databaseUsers);
        return(** html tree **);

    }
}   

我观察到组件的状态被设置了两次,一次是在渲染发生时,then promise 触发,第二次是在 promise 完成从数据库中获取数据时并设置 state.
我如何更好地控制它?就像实际上等待数据库上的数据,然后渲染?
欢迎任何提示。

还有其他方法可以实现您对多个组件所做的操作。 但是让我们坚持这个例子。

渲染两次没有错,因为你不想等待响应然后显示输出。

你可以有一个 loading 标志,这样你就可以显示 "loading" 代码,并在加载时显示输出。

或者您可以有 1 个管理工作的父组件:

class Parent extends Component {

    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            data: []
        }
    }

    componentDidMount() {
        this.setState({loading: true})
        axios.get('/users/get-users').then((response) => {
            this.setState({
                loading: false,
                data: response.data
            })
        });
    }

    render() {
        if (this.state.loading) {
            return <LoadingComponent />;
        }
        return <DataComponent data={this.state.data} />
    }
}