Я использую Search API для поиска репозиториев из Github. В настоящее время я могу искать репозитории, но я хочу отобразить имя репо и информацию на странице. Я создаю страницу в React. Как получить данные из файла JSON и добавить его на страницу?
let searchTerm;
const repositories = [];
class SearchBox extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
render() {
return(
<div>
<form>
<input type="text" className="searchbox" ref={(input) => { this.searchBox = input; }}/>
<button onClick={this.onClick}>Search</button>
</form>
<div className="foundRepo">{this.props.name}</div>
</div>
);
}
onClick(event) {
searchTerm = this.searchBox.value;
let endpoint = 'https://api.github.com/search/repositories?sort=stars&order=desc&q=' + searchTerm;
console.log(searchTerm);
fetch(endpoint)
.then(blob => blob.json())
.then(data => repositories.push(...data));
event.preventDefault();
}
}
И реагировать, и использовать API-интерфейсы для меня совершенно новые, поэтому код может быть немного грязным, но он работает. Просто нужна помощь в доступе к данным. Благодарю.
Сохраните данные ответа в состоянии компонента и переверните его с помощью .map
чтобы отобразить его. Вы должны прочитать о том, как работает состояние компонента.
let searchTerm;
class SearchBox extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.state = { repositories: [] };
}
render() {
return(
<div>
<form>
<input type="text" className="searchbox" ref={(input) => { this.searchBox = input; }}/>
<button onClick={this.onClick}>Search</button>
</form>
<div className="foundRepo">{this.props.name}</div>
<h2>Repositories</h2>
<ul>
{ this.state.repositories.map( ( item, index ) => (
<li key={ index }>
{ item.name }
</li>
)) }
</ul>
</div>
);
}
onClick(event) {
searchTerm = this.searchBox.value;
let endpoint = 'https://api.github.com/search/repositories?sort=stars&order=desc&q=' + searchTerm;
console.log(searchTerm);
fetch(endpoint)
.then(blob => blob.json())
.then(response => {
this.setState({ repositories: response.items });
});
event.preventDefault();
}
}