ReactJS-无法从api中找到导致错误的最新标题

时间:2019-09-30 19:26:51

标签: reactjs

我有一个着陆组件和一个NewsLatest组件。我正在使用一个api并尝试查找具有最新时间戳的文章,但我无法在reactJS中完成它。我检查了js代码,它可以正常工作,但在React中它没有呈现。请提出一些建议。

import React, { Component } from 'react'
import NewsSearch from '../NewsSearch/NewsSearch';
import NewsLatest from '../NewsLatest/NewsLatest';
import './Landing.css';
import axios from 'axios';


class Landing extends Component {
 state={
  newsList: []
 }
 componentDidMount(){
  axios.get(`https://api.nytimes.com/svc/topstories/v2/home.json?api-key=7cK9FpOnC3zgoboP2CPGR3FcznEaYCJv`)
  .then(res=> {
   this.setState({newsList: res.data.results});
  });

 }
 render() {
  // console.log(this.state.newsList);
  return (
   <div className="landing text-center text-white">
    <h1>News Portal</h1>

    <div className="news-search">
      <NewsSearch />
    </div>
     <div className="news-latest">
       <NewsLatest newsList={this.state.newsList}/>
     </div>
   </div>
  )
 }
}
export default Landing;

import React, { Component } from 'react';
// import PropTypes from 'prop-types';

class NewsLatest extends Component {
  constructor(props){
    super(props);
    this.state = {
             newsTitle:'',
             abstract:'',
             newsUrl:'',
            }
    // this.newsLatest = this.newsLatest.bind(this);
   }


   newsLatest = (e)=>{
    // e.preventDefault();
    const {newsList} = this.props;
    let maxTime = newsList.map(function(o) { 
       return new Date(o.updated_date);  
    });
     let maximumValue = Math.max(...maxTime);
     let latestnews = newsList.filter(function (el) {
          return maximumValue === new Date(el.updated_date).getTime();
          })[0];
     if(latestnews){
       this.setState({newsTitle: latestnews.title});
       return (<h4>{this.state.newsTitle}</h4>);
     }
   }
   newsTitle = () => (
    this.props.newsList.map(item => (<h2 key={item.title}>{item.title}</h2>))
  )
  render() {
    console.log(this.props.newsList);
    return (
      <div>
         <h2>News Latest....</h2>
         {this.newsLatest()}
      </div>
    );
  }
}


export default NewsLatest;

NewsLatest组件中的呈现存在一些问题。请提出一些建议。

1 个答案:

答案 0 :(得分:0)

尝试一下:

您可能必须获得最大深度误差,请改用生命周期方法,例如componentDidUpdate。仅当先前的道具与新的道具不同时才更新组件状态。

在此处了解更多信息:https://reactjs.org/docs/react-component.html

import React, { Component } from "react";
// import PropTypes from 'prop-types';

class NewsLatest extends Component {
  constructor(props) {
    super(props);
    this.state = {
      newsTitle: "",
      abstract: "",
      newsUrl: ""
    };
    // this.newsLatest = this.newsLatest.bind(this);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.newsList !== this.props.newsList) {
      const { newsList } = this.props;
      let maxTime = newsList.map(function(o) {
        return new Date(o.updated_date);
      });
      let maximumValue = Math.max(...maxTime);
      let latestnews = newsList.filter(function(el) {
        return maximumValue === new Date(el.updated_date).getTime();
      })[0];
      this.setState({ newsTitle: latestnews.title });
    }
  }

  // newsLatest = e => {
  //   // e.preventDefault();
  //   const { newsList } = this.props;
  //   let maxTime = newsList.map(function(o) {
  //     return new Date(o.updated_date);
  //   });
  //   let maximumValue = Math.max(...maxTime);
  //   let latestnews = newsList.filter(function(el) {
  //     return maximumValue === new Date(el.updated_date).getTime();
  //   })[0];
  //   console.log(latestnews)
  //   if (latestnews && latestnews.hasOwnProperty('length') && latestnews.length>0) {
  //     return <h4>{this.state.newsTitle}</h4>;
  //   }
  // };
  newsTitle = () =>
    this.props.newsList.map(item => <h2 key={item.title}>{item.title}</h2>);
  render() {
    console.log(this.props.newsList);
    return (
      <div>
        <h2>News Latest....</h2>
        <h4>{this.state.newsTitle}</h4>
      </div>
    );
  }
}

export default NewsLatest;

还有一个沙箱: https://codesandbox.io/s/hungry-frog-z37y0?fontsize=14