функция react setState не работает

#reactjs #event-handling

#reactjs #обработка событий

Вопрос:

Я новичок в react, и я пытался применить обработку событий в react, но столкнулся с некоторой проблемой при событии onclick. Когда вызывается кнопка «покажи мне Германию», страница затем зависает только при загрузке…

Вот код, который я написал..

 class App extends Component {
    constructor(props) {
        super(props);

        this.state = { articles: [],
                isLoaded:false ,
                country:'us'
                }
       
        this.change = this.change.bind(this);
    }


    componentDidMount() {
        const APIurl = `https://newsapi.org/v2/top-headlines?country=${this.state.country}amp;apiKey=${API_KEY}`;
        fetch(APIurl)
            .then(response => response.json())
            .then(json => {
                this.setState({
                    articles: json.articles,
                    isLoaded:true
                })
            })
    }
   // function to change the state
    change()
    {
        this.setState({
            articles: [],
            isLoaded:false ,
            country:"de"

        })
    }   
   
    render() {
      const { isLoaded,articles } = this.state;
      if(!isLoaded)
      {
          return (<h1>Loading....</h1>)
      }
     
        return (
            <div>
                <Navbar/>
                <button onClick={this.change}>show me of germany</button>
                <ul>
                    {articles.map(item=>(
                           <News item={item}/>
                    ))}
                </ul>
            </div>
       );
   }
}
export default App;
  

Надеюсь, вы поняли проблему

Комментарии:

1. Ну, единственное, что делает кнопка, это вызывает функцию, которая очищает данные и устанавливает isLoading состояние в false. Если вы хотите загрузить новые данные, вам нужно снова выполнить Ajax-запрос.

Ответ №1:

Вам нужно снова выполнить запрос.

 class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      articles: [],
      isLoaded: false,
      country:'us'
    }
       
    this.change = this.change.bind(this);
  }


  componentDidMount() {
    fetchData(this.state.country);
  }

  componentDidUpdate(prevProps, prevState) {
    const { country: prevCountry } = prevState;
    const { country: nextCountry } = this.state;

    if (prevCountry !== nextCountry) {
      fetchData(nextCountry);
    }
  }

  change() {
    this.setState({ country: 'de' });
  }

  fetchData(country) {
    this.setState({ articles: [], isLoaded: false });

    fetch(
      `https://newsapi.org/v2/top-headlines?country=${country}amp;apiKey=${API_KEY}`
    )
      .then(res => res.json())
      .then(({ articles }) => {
        this.setState({ articles, isLoaded: true });
      })
      .catch(console.error);
  }
   
  render() {
    //...
  }
}

export default App;