react.jsの初回処理(constructor)で、
axiosでバックエンド(express)にリクエストを行い、
返り値をstateに入れるような処理を作成したいと思っています。
下記の様な書き方で同期処理を行いたいのですが、
非同期になってしまいます。
どうすれば同期処理になりますでしょうか。
javascript
1 2constructor(props) { 3 super(props); 4 const main = () => { 5 console.log('axios start'); 6 axios 7 .get('http://localhost:3000/hogehoge') 8 .then((res)=>{ 9 console.log('axios res'); 10 return res; 11 }) 12 .catch((err)=>{ 13 console.log('axios null'); 14 return null; 15 }); 16 } 17 let res = main(); 18 console.log('axios end'); 19 this.state = { 20 hoge:res 21 } 22} 23... 24
理想:
axios start→axios res/null→axios end
実際:
axios start→axios end→axios res/null
await/async/promiseの把握のため一通り動かして把握し、
色々テストしたのですが、うまく動きませんでした。
まだ認識の抜けがあるのかもしれません...
ご教示のほどよろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/30 23:58