Вы можете делать то, что вам нравится, но обычно вы оставляете создание компонента (это не совсем HTML) на render
:
const API = 'https://randomuser.me/api/?results=5';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
logins: [],
};
}
componentDidMount() {
fetch(API)
.then(response => response.json())
.then(data => {
this.setState({logins: data.results});
})
}
render() {
return (
<div>
{this.state.logins.map((uname) => (
<div>
<button>{uname.login.username}</button>
</div>
))}
</div>
);
}
}
state
обычно должно содержать данные и оставьте отображение этих данных на render
.
Примечание: в вашем вызове fetch
отсутствуют две вещи:
Чекдля статуса ok
и
Обработчик ошибок
fetch(API)
.then(response => { // ***
if (!response.ok) { // ***
throw new Error({status: response.status}); // ***
} // ***
}) // ***
.then(response => response.json())
.then(data => {
// ...
})
.catch(err => { // ***
// Handle the error // ***
}); // ***
fetch
не отклоняет ошибки состояния, такие как 404.