我正在映射一系列项以生成图像,但是每次它将代码发送到无限循环中时。这是我的代码:

这是映射代码:

let mySrc = this.state.imageUrl;

{myImages.map(image => {
       this.getSrc(userId, image.id);

       return(
       <img src={mySrc}/>)
    })}

这是“getSrc”函数:
getSrc = async (userId, image) => {
    axios
      .get(`http://mysiteeee.com/api/getimage/${userId}/photo/${image}`, {
           auth: {
              username: 'username',
              password: 'password'
              },
              responseType: 'blob'
            })
      .then(res => {
          let myUrl = URL.createObjectURL(res.data)
          console.log(myUrl)
          this.setState({
              imageUrl: myUrl
              })
      })
      .catch(err => console.log(err))
    }

每当我转到该页面时,它就会反复遍历所有图像URL /图像。如何只显示图片网址/图片一次?如何停止无限拖曳图像?

这是整个组件的代码:
import React from 'react';
import axios from 'axios';

import HeaderTwo from './HeaderTwo';


class FullDescription extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            eventInfo: [],
            imageUrl: [],
            clicked: false,
        }
    }

    componentDidMount = () => {
        window.scrollTo(0,0);

        this.props.state.images.map(image =>
            this.getSrc(this.props.state.id, image.id))

        // this.getSrc(this.props.state.id, this.props.state.images[1].id)
    }

    changeClicked = (userId) => {
        if(this.state.clicked === false){
            this.setState({
                clicked: true
            })
        } else {
            this.setState({
                clicked: false
            })
        }
    }

    getSrc = async (userId, image) => {
        axios
            .get(`http://http://mysiteeee.com/api/getimage/${userId}/photo/${image}`, {
                auth: {
                    username: 'username',
                    password: 'password'
                    },
                    responseType: 'blob'
            })
            .then(res => {
                let myUrl = URL.createObjectURL(res.data)
                this.state.imageUrl.push(myUrl)

                // this.setState({
                //     imageUrl: myUrl
                //     })
            })
            .catch(err => console.log(err))
    }

    render() {
        let item = this.props.state;
        let date = new Date(item.date).toDateString();
        let time = new Date(item.date).toLocaleTimeString();
        let userId = this.props.state.id;
        let myImages = this.state.imageUrl;
        let checkMark = <button className='attend-button' onClick={() => this.changeClicked(userId)}>Attend Event</button>;

        console.log(myImages)

        if(this.state.clicked === true){
            checkMark = <button className='attend-button' onClick={() => this.changeClicked(userId)}>&#x2713; Attend Event</button>
        } else {
            checkMark = <button className='attend-button' onClick={() => this.changeClicked(userId)}>Attend Event</button>
        }

        return(
            <div>
                <HeaderTwo/>
                <body id="full-description-page">
                <div className='images-section'>
                    {myImages.map(mySrc => <img src={mySrc}/>)}
                </div>
                    <div id='heading-strip'>
                        <img src={myImages} className='heading-image'/>
                        <div className='heading-info'>
                            <p className='date'>{date}<br/>{time}</p>
                            <p className='name'>{item.name}</p>
                            <p className='location'><b>Location:</b> <br/>{item.location.name}, {item.location.address}, {item.location.city}, {item.location.state}</p>
                            <div className='button-area'>
                                    {checkMark}
                                </div>
                        </div>
                    </div>

                    <br/>
                    <p className='description'><b>Description:</b> {item.description}</p>


                    <br/><br/><br/><br/>
                    <p className='comments-header'><b>Comments:</b></p>
                    <div className='comments-section'>
                        {item.comments.map(comment =>
                            <div className='comments'>
                                <p>{comment.text}<br/><b>-{comment.from}</b></p>
                            </div>
                        )}
                    </div>
                </body>
            </div>
        )
    }
}

export default FullDescription;

最佳答案

代码中的问题是您要在render方法和getSrc中调用updating the state方法。



在这种情况下,React调用render方法,并且在render方法中存在状态更新,因此React再次调用render方法,并且该过程永远进行下去。

解决方案。

从render方法中删除this.getSrc并在getSrc生命周期挂钩中调用componentDidMount方法。

我也对map函数进行了小的更改。

例。

let myImages = this.state.imageUrl;

{myImages.map(mySrc => <img src={mySrc}/>)}

componentDidMount() {
 this.getSrc();
}

10-08 04:51