简体   繁体   中英

Component state variable as img src url

I am new to React. I am trying to set the src attribute of an image using a component state variable. But when I run the code I don't see the component getting rendered. However if I explicitly define src url of the image, it works.

My code is as follows. I am also using React carbon component and react grid layout.

import 'carbon-components/scss/globals/scss/styles.scss';
import GridLayout from 'react-grid-layout';

import React, { Component } from 'react';
import { ClickableTile,Link } from 'carbon-components-react';


class ct extends React.Component {

 constructor() {
  super()
  this.state ={
   arr:[]
  }
 }

 componentWillMount(){

   let tilesData = []

   fetch("https://xyz/api/abc")
   .then((results)=>{

      return results.json();

   }).then((data)=>{

        let details = {
            imageUrl:data.images["image"]
        }

        tilesData.push(details)
        this.setState({arr : tilesData})

   })



   render() {

   var layout = [
    {i: 'a', x: 0, y: 0, w: 2, h: 2}
   ];

   return (
   <GridLayout className="layout" layout={layout} rowHeight={30} width={50}>

   <ClickableTile key="a">

    <div>

    // issue here ---------VVVVV
    <img src={this.state.arr[0].imageUrl}/>

    </div>
    </ClickableTile>
   </GridLayout>
  );
  }
 }

What could be the issue?

UPDATE - I fixed the issue

FIX - this.state ={ arr:[{}] } }

Your fetch operation is asynchronous. You are changing the state without waiting for it to finish. You need to set the state in the fetch success callback for the setstate to take effect. Thus, your state is empty because the state was never changed.

Try this:

fetch("https://xyz/api/abc")
   .then((results)=>{

      return results.json();

   }).then((data)=>{

        let details = {
            imageUrl:data.images["image"]
        }

        tilesData.push(details)
        this.setState({arr : tilesData}) //call setState in the fetch callback
   })

I fixed it

this.state =
    {
        arr:[{}]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM