mirror of
https://github.com/reactjs/react.dev.git
synced 2026-02-24 20:53:08 +00:00
Handle more states in async example code
This commit is contained in:
@@ -31,30 +31,46 @@ The example API returns a JSON object like this:
|
||||
|
||||
```jsx
|
||||
class MyComponent extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
this.state = {
|
||||
isLoaded: false,
|
||||
error: null,
|
||||
items: [],
|
||||
}
|
||||
}
|
||||
|
||||
state = {
|
||||
error: null,
|
||||
isLoaded: false,
|
||||
items: []
|
||||
};
|
||||
|
||||
componentDidMount() {
|
||||
fetch('https://api.example.com/items')
|
||||
fetch("https://api.example.com/items")
|
||||
.then(res => res.json())
|
||||
.then(result => this.setState({items: result.items))
|
||||
.catch(err => this.setState({ err: error }))
|
||||
.then(result =>
|
||||
this.setState({
|
||||
isLoaded: true,
|
||||
items: result.items
|
||||
})
|
||||
)
|
||||
.catch(error =>
|
||||
this.setState({
|
||||
isLoaded: true,
|
||||
error
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
render() {
|
||||
const {error, items} = this.state
|
||||
if (err) return <div>{error}</div>
|
||||
return (
|
||||
<ul>
|
||||
{ items.map(item => <li>{item.name} {item.price}</li> }
|
||||
</ul>
|
||||
)
|
||||
const { error, items } = this.state;
|
||||
if (error) {
|
||||
return <div>Error: {error.message}</div>;
|
||||
} else if (!isLoaded) {
|
||||
return <div>Loading ...</div>;
|
||||
} else {
|
||||
return (
|
||||
<ul>
|
||||
{items.map(item => (
|
||||
<li key={item.name}>
|
||||
{item.name} {item.price}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user