【问题标题】:Why does my getImageId function only fire off the first time my code runs?为什么我的 getImageId 函数只在我的代码第一次运行时触发?
【发布时间】:2019-07-01 07:01:40
【问题描述】:

最初存在图像循环问题(它正在杀死我们的 api 调用)并意识到我们需要删除 componentDidUpdate。现在,当使用 React Dev Tools 检查页面时,我可以看到除了 img src 更新(包括 alt 标签)之外的所有内容。如果没有向页面呈现任何内容,那么它将正确呈现信息,但是一旦出现某些内容,它就会改变一切,除了图像本身。

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"
            }
        }
        />
    )
}

}

【问题讨论】:

  • 理论上,为什么您需要多次获取图像?
  • 图像数量不是问题,因为一旦游戏或游戏列表第一次渲染,除了游戏封面图像之外的所有内容都发生变化。
  • 解决方案还能用吗?

标签: reactjs axios


【解决方案1】:

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

componentDidMount() {
    this.getImageId();
}

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

任何时候更新状态或道具都会触发componentDidUpdate()。按照目前的构造,您的componentDidUpdate() 调用getImageId(),它会更新状态,然后触发componentDidUpdate(),然后它调用getImageId(),它......你明白了。

您可以解决此问题。如果您只想在新的src 作为您的父母的道具向下传递时对您的 API 进行重复调用。改为这样做:

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

所以现在,您只有在提供更新的src 时才提出新请求。

【讨论】:

  • 只要我只想一次渲染 1 个游戏并且如果你现在刷新页面就会中断。我计划一次渲染 5 到 10 个。
  • @TylerEdge 不错,希望在我输入此消息时它仍然有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 2012-08-13
  • 2011-03-25
  • 1970-01-01
  • 2016-12-03
  • 2018-07-01
  • 2021-10-18
相关资源
最近更新 更多