ReactJs ---向儿童发送道具,从而导致儿童渲染出现问题。UI 呈现未"NewsLatest.js"发生

  • 本文关键字:问题 发生 UI NewsLatest js ReactJs reactjs
  • 更新时间 :
  • 英文 :


一个组件Landing.js具有以下代码:

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;

当将 props 发送到 NewsLatest 组件时,会传递 2 个值:首先是未定义的,然后是当值出现时,然后是一个包含值的数组。

在"新闻最新.js"文件中的代码是:::

import React, { Component } from 'react';
// import PropTypes from 'prop-types';
class NewsLatest extends Component {
newsTitle = (
this.props.newsList.map(item => (<h2>{item.title}</h2>))
)
render() {
console.log(this.props.newsList);
return (
<div>
<h2>News Latest....</h2>
{this.newsTitle}
</div>
);
}
}

export default NewsLatest;

UI 上未呈现任何内容。我不知道如何处理。请提出一些建议。

您面临的问题是您没有渲染任何内容(本身(,因为newsTitle不返回任何内容。 在您的代码中,newsTitle是一个对象,但您需要使其成为一个函数。

修改NewsLatest应该可以解决这个问题

import React, { Component } from 'react';
// import PropTypes from 'prop-types';
class NewsLatest extends Component {
newsTitle = () => (
this.props.newsList.map(item => (<h2>{item.title}</h2>))
)
render() {
console.log(this.props.newsList);
return (
<div>
<h2>News Latest....</h2>
{this.newsTitle()}
</div>
);
}
}

export default NewsLatest;

最新更新