【问题标题】:Expected an assignment and instead saw an expression in reactjs期望一个分配,而是在 reactjs 中看到一个表达式
【发布时间】:2020-02-17 04:50:04
【问题描述】:

我是 Reactjs 的初学者。我正在尝试使用 fetch 从 jasonplaceholder api 获取 cmets 并显示它们。 我收到以下错误:- 预期分配或函数调用,而是看到一个表达式

Code

import React, { Component } from 'react'

export default class Comments extends Component {
    constructor() {
        super()
        this.state = {
            comments: []
        }
    }

    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/comments')
            .then(response => response.json())
            .then(comments => {
                this.setState({ comments: comments })
            });
    }

    render() {
        console.log(this.state.comments, "comments")
        return (
            <div className="conatiner">
                <p>All Comments :-</p>
                {
                    this.state.comments.map((comment) => {
                        <ul key={comment.id}>
                            <li>{comment.email}</li>
                            <li>{comment.body}</li>
                        </ul>
                    })
                }
            </div>
        )
    }
}

【问题讨论】:

  • 错字:在地图内添加return

标签: reactjs


【解决方案1】:

添加return,因为它是一个回调函数。

this.state.comments.map((comment) => {
  return (
    <ul key={comment.id}>
      <li>{comment.email}</li>
      <li>{comment.body}</li>
    </ul>
  );
})

更简单。

this.state.comments.map((comment) => (
    <ul key={comment.id}>
      <li>{comment.email}</li>
      <li>{comment.body}</li>
    </ul>
))

【讨论】:

    【解决方案2】:

    这将起作用(地图内的返回元素)

    this.state.comments.map((comment) => (
                            <ul key={comment.id}>
                                <li>{comment.email}</li>
                                <li>{comment.body}</li>
                            </ul>
                        ))
    

    reactjs中map的简单语法是

    array.map((element,index)=>(
    <h2>{element.name}</h2>
    ))
    

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 2020-11-20
      • 2019-05-09
      • 2017-09-09
      相关资源
      最近更新 更多