render()ってstateが変更されると実行されると思っていたのですが、なぜかその様になっていない様なのですが、、
以下の様なコードを書きました。
JS
1class merged extends Component { 2 constructor(props) { 3 super(props) 4 this.state = { 5 example:[], 6 loading:true 7 } 8 } 9 10 11 componentDidMount() { 12 console.log("componentDidMount") 13 this.get_example() 14 } 15 16 async get_example() { 17 const exa = await fetchExample() 18 const urls = await getUrlsFromKeys(headImages) 19 const examplesWithImage = exa.map( (ad , index) => { 20 ad.url = urls[index] 21 return ad 22 }) 23 24 this.setState( 25 { 26 example: examplesWithImage, 27 loading:false 28 29 } 30 31 ) 32 33 console.log(this.state.loading) 34 35 36 } 37 38 render() { 39 40 return( 41 42 <div > 43 <Show_example example = {this.state.example} loading = {this.state.loading}/> 44 </div> 45 46 ) 47 48 49 } 50 51}export default merged
JS
1class Show_example extends Component { 2 constructor(props) { 3 super(props) 4 this.state = { 5 example: this.props.example, 6 loading:this.props.loading 7 } 8 } 9 10 11 12 render() { 13 if(this.state.loading) { 14 console.log(this.state.loading) 15 return (省略) 16 }else{ 17 console.log(this.state.loading) 18 return (省略) 19 20 } 21 } 22 23}export default Show_example
コンポーネントShow_exampleの中ではthis.state.loading(Boolです)によって表示を変えたいのですがそれがうまくいきません。
logの出力を見るとまず最初はtrueなのでコンポーネントShow_exampleの中のconsole.logがtrueを表示します。次に"componentDidMount"が表示されます。
思っていたのは、この次に表示されるのはget_example()の中のlogが示すfalseでそこがfalseになったのでrenderが動きShow_exampleのlogがfalseを示すと思っていました。
しかし実際は"componentDidMount"が表示された後再度Show_exampleのlogがtrueを示し、最後にget_example()の中のlogが示すfalseを示しました。そのためShow_exampleの表示が変わりません。これはなぜでしょうか??
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/16 03:36