【发布时间】:2017-04-18 21:18:32
【问题描述】:
我对 React 非常陌生,目前正在做一个使用 GitHub API 通过 AJAX 返回搜索结果并能够在屏幕上列出该结果的小项目。目前我正在使用 for 循环来迭代响应数据并将该数据保存到变量中,很可能有更好的方法来做到这一点,但就像我说我是新人一样。然后我将状态设置为返回的数据。问题出在 setState 中,它只返回保存到变量的最后一个结果,而不是整个变量。下面列出的是整个组件,任何提示或建议将不胜感激。谢谢!
import axios from 'axios';
import * as React from 'react';
class User extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
name: name,
id: '',
userInput: '',
obj: null
};
}
handleSubmit(e: any) {
axios.get('https://api.github.com/users/' + this.state.userInput + '/repos')
.then((response) => {
if (response.data.length > 0) {
console.log('success');
let data1 = JSON.stringify(response.data);
let result = JSON.parse(data1);
for (let key in result) {
let obj = result[key];
let test = obj.name;
console.log(test);
this.setState({
name: name,
id: result[0].id,
obj: test,
userInput: this.state.userInput
})
};
} else {
console.log('else is working');
}
})
.catch((error) => {
console.log('error ');
});
}
render() {
return (
<div>
<form>
<input type="text" onChange={this.handleUserInput.bind(this)} value={this.state.userInput} />
<h1>{this.state.userInput}</h1>
<button type="button" onClick={this.handleSubmit.bind(this)}>Submit</button>
</form>
<h1>Name : {this.state.name}</h1>
<h1> ID : {this.state.id}</h1>
<h1>OBJ : {this.state.obj}</h1>
</div>
);
}
}
export default User;
安慰变量测试的结果给出了这个控制台输出 console output
但是,当 this.state.obj 在 obj 中设置它时,它只显示最后一项,如此处所示written to page
【问题讨论】:
-
您希望 API 的所有结果都显示在 UI 上?
标签: javascript reactjs typescript