简体   繁体   中英

How can i prevent endless request?

I am using two APIs. One of them fetching the country. Other of them is fetching language depending on the country. It works but when i checked the output on google console,there are too many requests increasing endless. How can i prevent that?

class Content extends React.Component {
    state = {
        country: [],
        languages: []
    }
    componentDidMount() {
        console.log("Country!!");
        API.fetchCountry().then(resp =>
            this.setState({ country: resp }));
    }
    LanguageFunction(country) {
        API.fetchLanguages(country).then(resp =>
            this.setState({ languages: resp }))
    }
    render() {
        console.log(this.state.country);
        console.log(this.state.languages)
        return (
            <MyCountry
                languages={this.state.languages}
                country={this.state.country}
                showLanguages={this.LanguageFunction.bind(this)}
            />
        );
    }
}

In this component Api requests are being sent.

class MyCountry extends React.Component {
    
    render() {
        const country = this.props.country;
        const languages = this.props.languages;

        return (
            <div>
                <span>{country}</span>
                {this.props.showLanguages(country)}
                <ul>
                    {languages.map((loc) => (
                        <li key={0}>
                            <span>{loc.name}</span>
                        </li>
                    ))}
                </ul>
            </div>)
    }
}

In this component,languages and the country are showed here and language function is being used here.

You are calling method showLanguages in child, which updates the parent state and causes re-render of child. Child again calls showLanguages, so you get an infinite loop. You should call showLanguages in your parent component and pass props to a child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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