简体   繁体   English

URL 未使用 setState 在 React JS 中更新

[英]URL is not updating in React JS using setState

I am building a news app using React JS.我正在使用 React JS 构建一个新闻应用程序。 I am using News API to collect the data.我正在使用新闻 API 来收集数据。 I added the next and previous buttons to show the next news by updating the URL using setState.我添加了下一个和上一个按钮,通过使用 setState 更新 URL 来显示下一个新闻。 But the problem is the URL is not updating.但问题是 URL 没有更新。 There is part of URL where &page=1 is and I want to change it to &page=2 and when I check it sends &page=NaN, I don't know why this is happening. &page=1 是 URL 的一部分,我想将它更改为 &page=2,当我检查它发送 &page=NaN 时,我不知道为什么会这样。 Here is the code:-这是代码:-

    import React, { Component } from "react";
import NewsItems from "./NewsItems";
import PreviousIcon from "@material-ui/icons/ArrowBack";
import NextIcon from "@material-ui/icons/ArrowForward";

export default class News extends Component {
  constructor() {
    super();

    this.state = {
      articles: [],
      loading: false,
    };
  }

  async componentDidMount() {
    let url =
      "https://newsapi.org/v2/top-headlines?country=in&apiKey=myapikey&page=1&pageSize=20";

    let data = await fetch(url);

    let parsedData = await data.json();
    this.setState({ articles: parsedData.articles });
  }

  handlePrev = async () => {
    console.log("previous");

    let url = `https://newsapi.org/v2/top-headlines?country=in&apiKey=myapikey&page=${
      this.state.page - 1
    }&pageSize=20`;

    let data = await fetch(url);

    let parsedData = await data.json();

    this.setState({
      page: this.state.page - 1,
      articles: parsedData.articles,
    });
  };

  handleNext = async () => {
    console.log("Next");

    let url = `https://newsapi.org/v2/top-headlines?country=in&apiKey=myapikey&page=${
      this.state.page + 1
    }&pageSize=20`;

    let data = await fetch(url);

    let parsedData = await data.json();

    this.setState({
      page: this.state.page + 1,
      articles: parsedData.articles,
    });
  };

  render() {
    return (
      <div className="news">
        <h1 className="head">SpiceHunt - Top headings</h1>
        <div className="news-items">
          {this.state.articles.map((element) => {
            return (
              <NewsItems
                key={element.url}
                title={element.title}
                description={element.description}
                img={element.urlToImage}
                tag={element.author}
                newsUrl={element.url}
              />
            );
          })}
        </div>
        <div className="pg-btn">
          <button
            className="page-btn"
            disabled={this.state.page <= 1}
            type="button"
            onClick={this.handlePrev}
          >
            <PreviousIcon /> Previous
          </button>
          <button className="page-btn" type="button" onClick={this.handleNext}>
            Next <NextIcon />
          </button>
        </div>
      </div>
    );
  }
}


 

I am a beginner in React JS and this is my first ever question in Stackoverflow.我是 React JS 的初学者,这是我在 Stackoverflow 中的第一个问题。 I have very high hope that I will get the solution.我非常希望我能得到解决方案。

Please add the page in state at initial time.请在初始时间添加state中的页面。

Older code:旧代码:

this.state = {
      articles: [],
      loading: false,
    };

Updated code:更新代码:

this.state = {
      articles: [],
      loading: false,
      page: 1
    };

You must use componentDidUpdate() for interact with state did changed.您必须使用 componentDidUpdate() 与 state 进行交互,确实发生了变化。 so in this case i use component did update when the state.page did not same with prevState.page so if that condition is true then we tell the react component to update acording to the function inside componentDidUpdate() .所以在这种情况下,当state.pageprevState.page不同时,我使用组件确实更新,所以如果该条件为真,那么我们告诉反应组件根据componentDidUpdate()内的 function 进行更新。 I just create some code in below:我只是在下面创建一些代码:

don't forget use spread operator or ... to keep previous state in our component.不要忘记使用spread operator...在我们的组件中保留以前的 state。 so when we update the state or setState its did'nt erase our previous state.所以当我们更新 state 或setState时,它并没有删除我们之前的 state。

You can see adjusted code below:您可以在下面看到调整后的代码:

import React, { Component } from "react";
import NewsItems from "./NewsItems";
import PreviousIcon from "@material-ui/icons/ArrowBack";
import NextIcon from "@material-ui/icons/ArrowForward";

export default class News extends Component {
  constructor() {
    super();

    this.state = {
      articles: [],
      loading: false,
      page: 1
    };
  }

  async componentDidMount() {
    let url =
      "https://newsapi.org/v2/top-headlines?country=in&apiKey=myapikey&page=1&pageSize=20";

    let data = await fetch(url);

    let parsedData = await data.json();
    this.setState({ ...this.state, articles: parsedData.articles });
  }

  async componentDidUpdate(_, prevState) {
   if (this.state.page !== prevState.page) {
        let url = `https://newsapi.org/v2/top-headlines? 
        country=in&apiKey=myapikey&page=${
        this.state.page
        }&pageSize=20`;

       let data = await fetch(url);

       let parsedData = await data.json();
       this.setState({
        ...this.state,
        articles: parsedData.articles,
       });
    }
  }

  handlePrev = async () => {
    console.log("previous");

    this.setState({
      ...this.state,
      page: this.state.page - 1,
    });
  };

  handleNext = async () => {
    console.log("Next");

    this.setState({
      ...this.state,
      page: this.state.page + 1,
    });
  };

  render() {
    return (
      <div className="news">
        <h1 className="head">SpiceHunt - Top headings</h1>
        <div className="news-items">
          {this.state.articles.map((element) => {
            return (
              <NewsItems
                key={element.url}
                title={element.title}
                description={element.description}
                img={element.urlToImage}
                tag={element.author}
                newsUrl={element.url}
              />
            );
          })}
        </div>
        <div className="pg-btn">
          <button
            className="page-btn"
            disabled={this.state.page <= 1}
            type="button"
            onClick={this.handlePrev}
          >
            <PreviousIcon /> Previous
          </button>
          <button className="page-btn" type="button" onClick={this.handleNext}>
            Next <NextIcon />
          </button>
        </div>
      </div>
    );
  }
}

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

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