首页 > 解决方案 > 解决:期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions

问题描述

嘿,我是该领域的新手,想使用地图显示状态,但我无法这样做
,通过 axios 的 api 调用没有问题,所以忽略它我的代码是

import React, { Component } from 'react';
import axios from 'axios';
const url ='https://www.reddit.com/r/space.json';
class Apicall extends Component {
state={
posts:[],
subr:'space'
};
componentDidMount(){
this.getReddit();
}
getReddit=async()=>{
console.log('getredddit called sir ');
try {
let response=await  axios.get(`https://www.reddit.com/r/${this.state.subr}.json`);
let posts=response.data.data.children.map(obj=>obj.data)
this.setState({posts:posts},()=>{console.log(this.state.posts);
})
} catch (error) {console.log(error);}}   
render() {
let controlItems=this.state.posts.map(post=>{<h1 id={post.id}>{post.title}</h1>});
return (
<div>
<h1>{`/r/${this.state.subr}`} </h1>                
{controlItems}
</div>);
}
}
export default Apicall;

标签: reactjs

解决方案


您在数据上迭代错误。response.data.data.children应替换为response.data.childrenet controlItems=this.state.posts.map(post=>{{post.title}})的隐式返回;也是错误的。

import React from "react";
import "./styles.css";
export default function App() {
  return (
    <div className="App">
      <Apicall />
    </div>
  );
}

class Apicall extends React.Component {
  state = {
    posts: [],
    subr: "space"
  };
  componentDidMount() {
    this.getReddit();
  }
  getReddit = async () => {
    console.log("getredddit called sir ");
    try {
      let response = await fetch(
        `https://www.reddit.com/r/${this.state.subr}.json`
      );
      response = await response.json();
      console.log(response);
      let posts = response.data.children.map(obj => obj.data);
      this.setState({ posts: posts }, () => {
        console.log(this.state.posts);
      });
    } catch (error) {
      console.log(error);
    }
  };
  render() {
    let controlItems = this.state.posts.map(post => (
      <h1 id={post.id}>{post.title}</h1>
    ));
    return (
      <div>
        <h1>{`/r/${this.state.subr}`} </h1>
        {controlItems}
      </div>
    );
  }
}


推荐阅读