首页 > 解决方案 > 使用 React.js 将数据绑定到前端

问题描述

我对 react.js 库很陌生。我正在尝试制作一个简单的 CRUD 应用程序。

我制作了一个名为dataprovider.js

export function getCrudData() {
    axios.get('https://api.github.com/users/fearcoder')
        .then(response => {
            this.setState({ githubdata: response.data });
        })
        .catch(function (error) {
            console.log(error);
        })
}

我已经导入了这个文件crudexample.js并调用了这样的方法:

constructor(props) {
        super(props);
        dataprovider.getCrudData();
    }

当我使用 F12 打开 Google 开发工具时,我可以看到 github 数据,因此工作正常。

现在我想绑定这些数据,我这样做了:

  <td>{githubdata.bio}</td>

我在我的谷歌开发工具中收到以下错误

'githubdata' 未定义 no-undef

有人可以指出我正确的方向吗?

标签: javascripthtmlnode.jsreactjsapi

解决方案


尝试以下操作:

constructor() {
    super(props);
    this.state = {
        githubdata: "" // Define githubdata.
    }
}

componentDidMount() {
    axios.get('https://api.github.com/users/fearcoder')
        .then(response => {
            this.setState({ githubdata: response.data });
        })
        .catch(function (error) {
            console.log(error);
        })
}

使成为:

<td>{this.state.githubdata.bio}</td>

组件DidMount()


推荐阅读