如何在 componentDidMount 中生成带有状态的动态 url?

How to generate dynamic url with state in componentDidMount?

我想在 componentDidMount 中用 {this.state.whatever} 动态化 URL 但失败了。因为状态值未定义(我运行 console.log 错误也显示了)

我以为在状态重置后 componentDidMount 运行s,所以我可以在 URL 中使用更新后的状态但是不起作用,我想知道为什么

state={ breed: "" }
async componentDidMount(){
   try {
       const res = await 
       fetch(`https://dog.ceo/api/breed/${this.state.breed}/images`);
       const data = await res.json();
       const imageUrl = data.message;
       this.setState({
         puppyImage: imageUrl
       })

   } catch (error) {
     console.log(error);
   }
 }

 onChangeHandler = event => {
   this.setState({breed: event.target.value})
 };

此 URL 不起作用,因为 {this.state.breed} 未定义,这意味着它尚未更新。 错误显示: GET https://dog.ceo/api/breed//images 404

componentDidMount() 只会在组件渲染后 运行 一次 一次 次,并且再也不会。

您应该使用 componentDidUpdate() 来代替,它会在组件获得更新状态或道具时触发。在其中,您可以配置逻辑以确定是否应该执行新的 fetch.

componentDidUpdate(prevProps, prevState){
   if(prevState.breed !== this.state.breed){
     try {
       const res = await 
       fetch(`https://dog.ceo/api/breed/${this.state.breed}/images`);
       const data = await res.json();
       const imageUrl = data.message;
       this.setState({
         puppyImage: imageUrl
       })

     } catch (error) {
       console.log(error);
     }
   }
 }

假设您所做的事情会改变 this.state.breed。上面定义的 componentDidUpdate() 逻辑将触发然后检查它们是否是先前的品种状态和更新的品种状态之间的差异。如果有,那么将对该品种进行新的获取调用,您将获得一个新的 puppyImage :).