为什么我的getImageId函数仅在我的代码首次运行时触发?

时间:2019-06-30 21:57:20

标签: reactjs axios

最初图像循环出现问题(这终止了我们的api调用),并意识到我们需要删除componentDidUpdate。现在,当使用React Dev Tools检查页面时,我可以看到除alt标签之外的所有img src更新。如果页面上未呈现任何内容,则它将正确呈现信息,但是一旦有内容,它将更改除图像本身之外的所有内容。

class Img extends Component {
constructor(props) {
    super(props)
    this.state = {
        src: ""
    }
}

// componentDidUpdate() {
//     this.getImageId();
// }
componentDidMount() {
    this.getImageId();
}

getImageId() {
    axios.get(`http://localhost:4000/api/images/${this.props.src}`)
        .then(response => {
            console.log(response.data) //this shows only on first request
            this.setState({
                src: response.data
            })
        })
        .catch(err => console.log(err))
}
render() {
    return ( <img src = {
            this.state.src
        }
        alt = {
            this.props.alt
        }
        style = {
            {
                height: "150px",
                width: "200px",
                borderRadius: "10px"
            }
        }
        />
    )
}

}

1 个答案:

答案 0 :(得分:1)

照原样,您的组件只会一次发出一个API请求。该逻辑在componentDidMount()中执行。这是一个lifecycle事件,在第一次呈现组件后立即执行,以后不再执行。

componentDidMount() {
    this.getImageId();
}

您注释掉的componentDidUpdate()逻辑正在创建一个无限循环。首先,您的初始getImageId()调用在componentDidMount()中运行。它发出一个API请求,然后响应一些数据,然后使用该数据更新组件状态。

任何时间状态或道具更新都会触发componentDidUpdate()。按照目前的构造,您的componentDidUpdate()调用getImageId(),该更新会更新状态,然后触发componentDidUpdate(),然后触发getImageId(),从而得到图片。 / p>

您可以解决此问题。如果您只想在父项将新的src传递为道具时对API进行周期性调用。改为这样做:

componentDidUpdate(prevProps){
   if(this.props.src !== prevProps.src){
      this.getImageId()
   }
}

因此,现在,您仅在提供更新的src时发出新请求。

相关问题