我有一个标志列表,单击这些标志可以更改应用程序的语言,并且当前的语言标志会变大。
对于当前语言,我正在使用一个不同的API,该API需要执行异步过程。第一次运行该应用程序时它可以工作,但是当我尝试更改该应用程序时,语言会更改,但标志保持不变。
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 />
);
}
}
在我的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>
答案 0 :(得分:3)
尝试一下:
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 />
);
}
}