【问题标题】:How do I call 2 api in one class so that both work? (React)如何在一个类中调用 2 个 api 以便两者都工作? (反应)
【发布时间】:2021-03-25 03:33:49
【问题描述】:

我想在一个类中调用 api 两次,但是当我调用另一个类时,第一个不再起作用。我该怎么办?

这是代码 ---> P.S 这只是一个请求代码。我不写渲染代码

export class  Ajax1 extends Component{
    constructor(props){
        super(props)
        this.state={
            info:[],
            info2:[]
        }
    }

    async componentDidMount(){
        const url="https://jsonplaceholder.typicode.com/users"
        const res=await fetch(url)
        const data= await res.json()
        this.setState({info:data})
    }

    async componentDidMount(){
        const url="https://jsonplaceholder.typicode.com/posts"
        const res=await fetch(url)
        const data= await res.json()
        this.setState({info2:data})
    }

【问题讨论】:

    标签: reactjs ajax api rxjs frontend


    【解决方案1】:

    同一类中不应有多个 componentDidMount 函数:

    async componentDidMount(){
        this.fetchInfo();
        this.fetchInfo2()
    }
    
    async fetchInfo(){
        const url="https://jsonplaceholder.typicode.com/users"
        const res=await fetch(url)
        const data= await res.json()
        this.setState({info:data})
    }
    
    async fetchInfo2(){
        const url="https://jsonplaceholder.typicode.com/posts"
        const res=await fetch(url)
        const data= await res.json()
        this.setState({info2:data})
    }
    

    【讨论】:

    • 要跟进这个,如果你只想更新一次状态,当两个 API 调用都完成时,你可以在 componentDidMount 函数中使用 Promise.whenAll() 来只设置两个时的状态承诺已经完成。
    • 是的,你是对的,我会更新我的答案,谢谢
    • 另外我推荐你使用 Promise.all。
    • 哦,是的,对不起,我把这个名字和 C# 的 Task.WhenAll 搞混了。
    猜你喜欢
    • 2021-05-13
    • 2021-02-10
    • 1970-01-01
    • 2022-01-10
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多