Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 这是React and Axios then promise的正确用法吗?_Reactjs_Promise_Axios - Fatal编程技术网

Reactjs 这是React and Axios then promise的正确用法吗?

Reactjs 这是React and Axios then promise的正确用法吗?,reactjs,promise,axios,Reactjs,Promise,Axios,我将axios用于React项目,我想知道在这种情况下使用then promise是否正确。 基本上,当组件呈现时,我使用axios从数据库获取数据 class Participants extends React.Component{ constructor(props){ super(props); this.state = { databaseUsers: [], } this.getUse

我将axios用于React项目,我想知道在这种情况下使用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 **);

    }
}   
我观察到组件的状态设置了两次,一次是在渲染时,然后promise启动,第二次是在promise从数据库获取数据并设置状态时。 我怎样才能更好地控制这一切?比如说,实际等待数据库中的数据,然后进行渲染?
欢迎任何提示

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

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

您可以有一个加载标志,以便显示加载代码,并在加载时显示输出

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

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} />
    }
}

我不希望我的状态是这样的吗?在componentDidMount中设置状态{loading:true}?是的,我错了。复制粘贴:axios.loadUsers是我提供的函数吗?在哪里发挥作用?谢谢,这是一个优雅的解决方案。