[英]Binding data to front-end with 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>
我的Google开发工具出现以下错误
未定义'githubdata'no-undef
有人可以指出我正确的方向吗?
请尝试以下操作:
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>
您可以编写如下代码:
dataProvider.js
export function getCrudData() {
return axios
.get("https://api.github.com/users/fearcoder")
.then(response => {
return response;
})
.catch(function(error) {
console.log(error);
});
}
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>
</>
);
}
请看演示以获得更好的说明。
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.