File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -82,3 +82,50 @@ class MyComponent extends React.Component {
82
82
}
83
83
}
84
84
```
85
+
86
+ Here is the equivalent with [ Hooks] ( https://reactjs.org/docs/hooks-intro.html ) :
87
+
88
+ ``` js
89
+ function MyComponent () {
90
+ const [error , setError ] = useState (null );
91
+ const [isLoaded , setIsLoaded ] = useState (false );
92
+ const [items , setItems ] = useState ([]);
93
+
94
+ // Note: the empty deps array [] means
95
+ // this useEffect will run once
96
+ // similar to componentDidMount()
97
+ useEffect (() => {
98
+ fetch (" https://api.example.com/items" )
99
+ .then (res => res .json ())
100
+ .then (
101
+ (result ) => {
102
+ setIsLoaded (true );
103
+ setItems (result .items );
104
+ },
105
+ // Note: it's important to handle errors here
106
+ // instead of a catch() block so that we don't swallow
107
+ // exceptions from actual bugs in components.
108
+ (error ) => {
109
+ setIsLoaded (true );
110
+ setError (error);
111
+ }
112
+ )
113
+ }, [])
114
+
115
+ if (error) {
116
+ return < div> Error : {error .message }< / div> ;
117
+ } else if (! isLoaded) {
118
+ return < div> Loading... < / div> ;
119
+ } else {
120
+ return (
121
+ < ul>
122
+ {items .map (item => (
123
+ < li key= {item .name }>
124
+ {item .name } {item .price }
125
+ < / li>
126
+ ))}
127
+ < / ul>
128
+ );
129
+ }
130
+ }
131
+ ```
You can’t perform that action at this time.
0 commit comments