简体   繁体   English

componentDidMount 中的异步功能在第二个挂载反应中不起作用

[英]Async function in componentDidMount doesn't work on second mount react

I've got a list of flags that when clicked on change the language of my app and the current language flag gets bigger.我有一个标志列表,当点击这些标志时会更改我的应用程序的语言,并且当前的语言标志会变大。

For the current language, I'm using a different API that requires me to do an async process.对于当前的语言,我使用的是不同的 API,它要求我执行异步过程。 It works when I run the app for the first time, but when I try to change it, the language changes, but the flag stays the same.当我第一次运行应用程序时它可以工作,但是当我尝试更改它时,语言会发生变化,但标志保持不变。

export default class FlagImage extends Component {
  state = {};
  componentDidMount() {
    this.getFlag();
    console.log("mounted"); //hundreds of logs
  }
  getFlag = async (name = this.props.name) => {
    const url = `https://restcountries.eu/rest/v2/alpha/${name}`;
    const res = await fetch(url);
    const json = await res.json();
    const flagURL = json.flag;
    this.setState({ flagURL });
  };

  render() {
    const { name, big } = this.props;

    return name ? (
      big ? (
        <img alt={`Flag ${name}`} src={this.state.flagURL} width="87px" height="58px" />
      ) : (
        <img alt={`Flag ${name}`} src={`https://www.countryflags.io/${name}/flat/32.png`} />
      )
    ) : (
      <div />
    );
  }
}

in my jsx:在我的 jsx 中:

        <div //this div works like a button
          className={styles["flag2"]}
          onClick={() => {
            this.setState({ open: !this.state.open });
          }}>
          <FlagImage name={this.getCountryCode()} big={true} />
        </div>

try this:尝试这个:

export default class FlagImage extends Component {
  state = {};
  componentDidMount() {
    this.getFlag();
    console.log("mounted"); //hundreds of logs
  }

  componentDidUpdate(prevProps, prevState, snapshot){
     if (this.props.name !== prevProps.name || this.props.big !== prevProps.big) {
            this.getFlag();
     }
  }

  getFlag = async (name = this.props.name) => {
    const url = `https://restcountries.eu/rest/v2/alpha/${name}`;
    const res = await fetch(url);
    const json = await res.json();
    const flagURL = json.flag;
    this.setState({ flagURL });
  };

  render() {
    const { name, big } = this.props;

    return name ? (
      big ? (
        <img alt={`Flag ${name}`} src={this.state.flagURL} width="87px" height="58px" />
      ) : (
        <img alt={`Flag ${name}`} src={`https://www.countryflags.io/${name}/flat/32.png`} />
      )
    ) : (
      <div />
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM