【问题标题】:reactjs check for data updatereactjs 检查数据更新
【发布时间】:2019-12-07 18:24:26
【问题描述】:

我有 GUser 类,在我的项目中存储来自 GitHub-api 的数据并处理它们:

import axios from "axios";
export default class GUser {
    constructor(userName) {
        this.userName=userName;
        this.getUserData(this,userName);
    }
    getUserData(that, userName) {
        if(that.data===undefined)
        {
            axios.get('https://api.github.com/users/'.concat(userName))
                .then(function (response) {
                    that.data = response.data;
                    console.log(that);
                    return that.data;
                })
                .catch(function (error) {
                    console.log(userName+ " got error " +error);
                });
        }
        else{return that.data;}
    }
}

我正在尝试同步页面,所以我在TestRender 中写道:

import React from 'react';
import GUser from "../model/GUser";
class TestRender extends React.Component{
    userName='maifeeulasad';
    user=new GUser(this.userName);
    componentWillMount() {
        try {
            console.log(this.user.getUserData());
        }
        catch (e) {console.log(e);}
    }
    componentDidMount() {
        try {
            console.log(this.user.getUserData());
        }
        catch (e) {console.log(e);}
    }
    render() {
        return(
            <div>
            </div>
        );
    }
}
export default TestRender;

我的目标是在收到数据后立即在控制台记录数据。

我该怎么做?

以前,当我从同一个脚本加载数据时,我只使用了componentWillMount。它目前给了我TypeError: Cannot read property 'data' of undefined,可能是因为我没有在GUser 中将data 指定为state,但它是通过时间创建的吧?

【问题讨论】:

标签: javascript reactjs asynchronous axios


【解决方案1】:

看起来您正在使用对象的属性来存储状态的组件,这并不好,因为当这些值更新时,React 不会重新渲染组件。
TestRender 的每个实例都应该有userNameuser 的值是否作为属性?这些值总是一样的吗?如果没有,请使用useState

另外,componentDidMountcomponentWillMount 只会在组件被挂载时被调用,此时你还没有完成获取,所以你还没有要打印的值。这是一个异步问题。

要处理异步挑战,我建议使用useEffect

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多