简体   繁体   English

组件状态变量为img src url

[英]Component state variable as img src url

I am new to React. 我是React的新手。 I am trying to set the src attribute of an image using a component state variable. 我正在尝试使用组件状态变量设置图像的src属性。 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. 但是,如果我显式定义图像的src url,则它可以工作。

My code is as follows. 我的代码如下。 I am also using React carbon component and react grid layout. 我也在使用React Carbon组件和React网格布局。

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:[{}] } } FIX- this.state ={ arr:[{}] } }

Your fetch operation is asynchronous. 您的fetch操作是异步的。 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. 您需要在fetch成功回调中设置状态,以使setstate生效。 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:[{}]
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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