【问题标题】:React array.map returns Expected an assignment or function call and instead saw an expressionReact array.map 返回预期的赋值或函数调用,而是看到一个表达式
【发布时间】:2020-08-26 13:23:50
【问题描述】:

我编写了一个非常简单的反应组件,我尝试从 jsonplaceholder/typicode 网站获取 API。我能够成功获得结果并将其设置为状态。现在,当我尝试使用 array.map 在屏幕上打印这些结果时,我收到以下错误

Expected an assignment or function call and instead saw an expression  no-unused-expressions

这是组件的样子:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      result: []
     }
  }

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts")
    .then(res=> res.json())
    .then(result=>{
      this.setState({
        result
      })
    })
  }
  
  render() { 
    return ( 
      <div>
        {this.state.result.map(post=>{
          <h1>{post.title}</h1>
        })}
      </div>
     );
  }
}

我不明白我在这里做错了什么。有人请看一下

【问题讨论】:

    标签: javascript arrays reactjs javascript-objects array-map


    【解决方案1】:

    你忘了return

    <div>
      {this.state.result.map((post) => {
        return <h1>{post.title}</h1>
      })}
    </div>
    
    

    用于演示的 Codesandbox

    【讨论】:

    • 非常感谢。有时你确实需要第二双眼睛来发现一个愚蠢的错误。不过,再次感谢。
    猜你喜欢
    • 2020-02-12
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2022-01-14
    • 2021-04-19
    • 1970-01-01
    • 2017-09-09
    相关资源
    最近更新 更多