获得预期的赋值或函数调用,而是在尝试在 React 中呈现组件时看到表达式 no-unused-expressions 错误

IT技术 javascript reactjs
2021-05-26 15:53:19

我正在尝试Card根据items对象中的项目数呈现组件,但在第 6 行出现错误。

import React from "react";
    export class Cards extends React.Component {
      render() {
        let elements = [];
        elements = this.props.items.map(item => {
          <Card titles = {item.title} imgsrc = {item.urlToImage}
          discr = {item.description} urls = {item.url}
          />
        })
        return (
          {elements}
        );
      }
    }

这是Card组件:

import React from 'react'
export default ({titles, imgsrc, urls, discr}) => {
  return (
    <div className="cards">
        <div className="card">
          <div className="cardHead">
            <h4>{titles}</h4>
          </div>
          <div className="cardBody">
            <img src={imgsrc} alt="pst-img" />
          </div>
          <div className="cardFooter">
            <p>{discr}</p>
            <a className="buttn" href={urls}>
              <button>Read More</button>
            </a>
          </div>
        </div>
      </div>
    )
 }
2个回答

.map不需要像这样返回 JSX

import React from "react";
    export class Cards extends React.Component {
      render() {
        let elements = [];
        elements = this.props.items.map(item => {
         return <Card titles = {item.title} imgsrc = {item.urlToImage}
          discr = {item.description} urls = {item.url}
          />
        })
        return (
          {elements}
        );
      }
    }

或者以更清洁的方式:

import React from "react";
    export class Cards extends React.Component {
      render() {
        return (
         {this.props.items.map(item => {
         return <Card titles = {item.title} imgsrc = {item.urlToImage}
          discr = {item.description} urls = {item.url}
          />
        })}
        );
      }
    }

作为第一个答案,您需要返回 JSX map()

或者使用( )而不是在{}里面map()

像这样

import React from "react";
    export class Cards extends React.Component {
      render() {
        return (
         {this.props.items.map(item => (
         return <Card titles = {item.title} imgsrc = {item.urlToImage}
          discr = {item.description} urls = {item.url}
          />
        ))}
        );
      }
    }