[英]Binding data to front-end with React.js
I am very new with the react.js library. 我对react.js库非常陌生。 I am trying to make a simple CRUD application.
我正在尝试制作一个简单的CRUD应用程序。
I have made a file called dataprovider.js
我制作了一个名为
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);
})
}
I have imported this file in crudexample.js
and called the method like this: 我已经在
crudexample.js
导入了此文件,并调用了如下方法:
constructor(props) {
super(props);
dataprovider.getCrudData();
}
When I open Google dev tools with F12 I can see the github data so that's working fine. 当我使用F12打开Google开发工具时,我可以看到github数据,因此工作正常。
Now I want to bind this data and I did it like this: 现在,我想绑定这些数据,我这样做是这样的:
<td>{githubdata.bio}</td>
I get the following error in my google dev tools 我的Google开发工具出现以下错误
'githubdata' is not defined no-undef
未定义'githubdata'no-undef
Can someone point me in the right direction? 有人可以指出我正确的方向吗?
Try the following: 请尝试以下操作:
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);
})
}
Render: 渲染:
<td>{this.state.githubdata.bio}</td>
You can write the code as follows : 您可以编写如下代码:
dataProvider.js dataProvider.js
export function getCrudData() {
return axios
.get("https://api.github.com/users/fearcoder")
.then(response => {
return response;
})
.catch(function(error) {
console.log(error);
});
}
crudeExample.js rawExample.js
constructor(props) {
super(props);
this.state = {
githubdata: ""
};
}
componentWillMount() {
getCrudData().then(res => {
console.log(res);
this.setState({ githubdata: res.data });
});
}
render() {
const { githubdata } = this.state;
return (
<>
<div>{githubdata.url}</div>
</>
);
}
Look at the demo for better clarification. 请看演示以获得更好的说明。
https://codesandbox.io/embed/upbeat-leftpad-isrm5 https://codesandbox.io/embed/upbeat-leftpad-isrm5
:)) :))
githubdata
是在state
定义的,因此使用它可以访问githubdata
:
this.state.githubdata
尝试这个:
<td>{this.state.githubdata.bio}</td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.