代码之家  ›  专栏  ›  技术社区  ›  Goji Berry

无法用映射函数绑定JSON数据

  •  -1
  • Goji Berry  · 技术社区  · 6 年前

    例如,下面有一个JSON,我需要 name 属于 genres .

    {
      "adult": false,
      "backdrop_path": "/5qxePyMYDisLe8rJiBYX8HKEyv2.jpg",
      "budget": 178000000,
      "genres": [
        {
          "id": 12,
          "name": "Adventure"
        },
        {
          "id": 28,
          "name": "Action"
        },
        {
          "id": 53,
          "name": "Thriller"
        }
      ],
      "homepage": null
    }
    

    但是当我使用map函数时,React返回一个错误:

    类型错误:this.state.persons.map不是函数

    class Content extends React.Component {
        state = {
            persons: []
        }
    
        componentDidMount() {
            axios.get(Config.apiUrl + 353081 + Config.apiKey)
                .then(res => {
                    const persons = res.data;
                    this.setState({ persons });
                })
        }
    
        render() {
            return (
                <div>
                    <Grid>
                        <Grid item xs={9}>
                            <Typography gutterBottom={true}><b>Budget:</b> { this.state.persons.budget }</Typography>
                            <Typography gutterBottom={true}><b>Genres:</b> { this.state.persons.map(person => <li key={person.genres.id}>{person.genres.name}</li>) }</Typography>
                        </Grid>
                    </Grid>
                </div>
            );
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Arup Rakshit    6 年前

    我认为你说的应该是一个字面上的对象 {} ,不是 [] . 阿尔索 res.data 返回 {..} ,不是 [] . 如果它返回一个数组,那么 this.state.persons.budget 应该会抛出错误,但不会。这证明了, persons 状态不是数组。

    state = {
      persons: {
        genres: []
      }
    }
    

    然后

    <Typography gutterBottom={true}>
      <b>Genres:</b>{" "}
      {this.state.persons.genres.map(genre => <li key={genre.id}>{genre.name}</li>)}
    </Typography>;