使用axios时如何在javascript中停止无限循环?

问题描述 投票:2回答:3

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

这是映射代码:

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;

javascript reactjs infinite-loop react-state
3个回答
0
投票

您正在使用::更改状态的事实>

   this.setState({
      imageUrl: myUrl
   })

并且同时在渲染函数中使用this.state.imageUrl,使其连续循环,因为每次渲染时,它都会再次开始执行array.map,并且array.map调用将触发新的状态更新。 ..因此它会永远循环。


1
投票

与您的代码有关的问题是,您正在render方法和getSrc中调用updating the state方法。


0
投票

此外,我认为您可能需要使用地图”

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

   return(
   <img src={mySrc}/>)
})}
© www.soinside.com 2019 - 2024. All rights reserved.