代码之家  ›  专栏  ›  技术社区  ›  user9013856

react map不是一个函数

  •  2
  • user9013856  · 技术社区  · 6 年前

    代码如下:

    import React, { Component } from 'react'
    import axios from 'axios';
    
    
    class Contacts extends Component {
     constructor(){
     super();
    
     this.state = {
        contacts: [],
     }
    
    }
    
    
    componentDidMount(){
        axios.get('url')
        .then(response => {
        this.setState({ contacts: response.data });
        })
        .catch(function (error) {
        console.log(error);
        })
    }
    
    
    render() {
        const { contacts } = this.state 
        return(
        <div>
            {contacts.map(contact => (
                <h1>contact.hello</h1>
            ))}
    
        </div>
        )
    }
    }
    
    export default Contacts;
    

    那么我如何渲染这个对象呢?

    它现在有一个属性,但以后会有更多属性:trued JSON.stringify(obj)

    {hello: "test"}
    
    4 回复  |  直到 6 年前
        1
  •  3
  •   Hemadri Dasari    6 年前

    因为联系人是一个对象,所以我建议您在其上执行object.keys,然后执行.map,这样您就可以获得对象键及其值。

    还有一件事,当您迭代数据数组或下面这样的对象时,千万不要忘记向父jsx元素添加惟一键。

     <div>
        {Object.keys(contacts).map((name, index) => (
            <h1 key={'Key'+index}>{contacts[name]}</h1>
        ))}
    
    </div>
    
        2
  •  5
  •   Nicola Peluchetti    6 年前

    contacts response.data

    componentDidMount

        3
  •  2
  •   Asaf Aviv    6 年前

    从react文档:

    这些方法被认为是遗留的,您应该 avoid them 在新代码中:

    当你想包装一个对象,你可以简单地包装它在括号里

    class Contacts extends Component {
      constructor() {
        super();
    
        this.state = {
          contacts: [],
        }
      }
    
      componentDidMount() {
        axios.get('url')
          .then(({ data }) => {
            this.setState({ contacts: [data] });
          })
          .catch((error) => {
            console.log(error);
          });
      }
    
      render() {
        const { contacts } = this.state;
        return (
          <div>
            {contacts.map(contact => (
              <h1 key={/* unique key */}>contact.hello</h1>
            ))}
          </div>
        );
      }
    }
    
        4
  •  0
  •   davidev    6 年前

    在装入组件之前,使用async await获取响应

    import React, { Component } from 'react'
    import axios from 'axios';
    
    
    class Contacts extends Component {
      constructor(){
       super();
    
       this.state = {
          contacts: [],
       }
      }
    
      async componentWillMount(){
        const response = await axios.get('url')
        this.setState({ contacts: response.data })
      }
    
      render() {
          const { contacts } = this.state
          return(
          <div>
              {contacts.map(contact => (
                  <h1>contact.hello</h1>
              ))}
    
          </div>
          )
       }
    }
    
    export default Contacts;