質問編集履歴
2
コード修正
test
CHANGED
File without changes
|
test
CHANGED
@@ -319,3 +319,9 @@
|
|
319
319
|
}
|
320
320
|
|
321
321
|
```
|
322
|
+
|
323
|
+
|
324
|
+
|
325
|
+
## 出力
|
326
|
+
|
327
|
+
![イメージ説明](f2562fd91294776a8cdbf50beec4dd3e.png)
|
1
ソース追記
test
CHANGED
File without changes
|
test
CHANGED
@@ -207,3 +207,115 @@
|
|
207
207
|
|
208
208
|
|
209
209
|
```
|
210
|
+
|
211
|
+
|
212
|
+
|
213
|
+
# 修正後ソース
|
214
|
+
|
215
|
+
```javascript
|
216
|
+
|
217
|
+
|
218
|
+
|
219
|
+
# context/PostsContext.jsx
|
220
|
+
|
221
|
+
|
222
|
+
|
223
|
+
import {createContext, useState} from "react";
|
224
|
+
|
225
|
+
import {useEffect} from "react";
|
226
|
+
|
227
|
+
|
228
|
+
|
229
|
+
|
230
|
+
|
231
|
+
const PostsContext = createContext({});
|
232
|
+
|
233
|
+
|
234
|
+
|
235
|
+
const PostsProvider = ({children}) => {
|
236
|
+
|
237
|
+
|
238
|
+
|
239
|
+
const [posts, setPosts] = useState({})
|
240
|
+
|
241
|
+
|
242
|
+
|
243
|
+
useEffect(async () => {
|
244
|
+
|
245
|
+
|
246
|
+
|
247
|
+
const res = await fetch('xxxxxxx/wp-json/wp/v2/posts');
|
248
|
+
|
249
|
+
const posts = await res.json();
|
250
|
+
|
251
|
+
|
252
|
+
|
253
|
+
setPosts(posts);
|
254
|
+
|
255
|
+
|
256
|
+
|
257
|
+
}, [setPosts])
|
258
|
+
|
259
|
+
|
260
|
+
|
261
|
+
return (
|
262
|
+
|
263
|
+
<PostsContext.Provider value={{posts}}>
|
264
|
+
|
265
|
+
{children}
|
266
|
+
|
267
|
+
</PostsContext.Provider>
|
268
|
+
|
269
|
+
)
|
270
|
+
|
271
|
+
|
272
|
+
|
273
|
+
}
|
274
|
+
|
275
|
+
|
276
|
+
|
277
|
+
export {PostsContext, PostsProvider};
|
278
|
+
|
279
|
+
|
280
|
+
|
281
|
+
```
|
282
|
+
|
283
|
+
|
284
|
+
|
285
|
+
```javascript
|
286
|
+
|
287
|
+
|
288
|
+
|
289
|
+
# pages/index.js
|
290
|
+
|
291
|
+
|
292
|
+
|
293
|
+
import Head from 'next/head'
|
294
|
+
|
295
|
+
import {useContext} from "react";
|
296
|
+
|
297
|
+
import {PostsContext} from "../contexts/PostsContext";
|
298
|
+
|
299
|
+
|
300
|
+
|
301
|
+
export default function Home() {
|
302
|
+
|
303
|
+
|
304
|
+
|
305
|
+
const {posts} = useContext(PostsContext);
|
306
|
+
|
307
|
+
|
308
|
+
|
309
|
+
console.log(posts);
|
310
|
+
|
311
|
+
|
312
|
+
|
313
|
+
return (
|
314
|
+
|
315
|
+
<></>
|
316
|
+
|
317
|
+
)
|
318
|
+
|
319
|
+
}
|
320
|
+
|
321
|
+
```
|