javascript - 如何在 ReactJS 中渲染对象数组

标签 javascript reactjs

我想获取使用 reactJS 15.5 的用户列表,代码:

 constructor(props) {
   super(props);
        this.state = {
            values: []
        };
        this.getDataFromUser = this.getDataFromUser.bind(this);
    }

 render() {
        return (
            <div>
                <button onClick={this.getDataFromUser}>Fetch</button>
                <p>
                    {this.state.values}
                </p>
            </div>
        );
    }

 getDataFromUser(){
        fetch('http://localhost:8000/api/user')
            .then(response => response.json())
            .then(json => {
                console.log(json);
                this.setState({values: json })
        })
    }

console.log(json) 中,我得到 enter image description here

但是当我点击按钮 Fetch 时出现此错误,因此 getDataFromUser 中出现错误:

Unhandled Rejection (Invariant Violation): Objects are not valid as a React child (found: object with keys {id, nom, prenom, email,is_admin,created_at, updated_at}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

创建用户对象是有原因的,所以任何人都可以帮助我解决这个问题,谢谢

最佳答案

它是一个对象数组,因此您需要使用map 来迭代数组然后呈现特定值。

像这样:

render() {
    return (
        <div>
            <button onClick={this.getDataFromUser}>Fetch</button>
            <p>
                {this.state.values.map(el => {
                    return <div key={el.id}>
                       <span>{el.email}</span>
                       <span>{el.nom}</span>
                       <span>{el.is_manager}</span>
                    </div>
                })}
            </p>
        </div>
    );
}

关于javascript - 如何在 ReactJS 中渲染对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154951/

相关文章:

reactjs - React Google 登录内联样式

javascript - 如何通过 Javascript 中的表单数据附加对象数组

javascript - 为什么 JQuery .html() 不适用于单个 div 标签?

javascript - 更新组件不起作用 ReactJs

javascript - Heroku 构建 MERN 堆栈 Web 应用程序失败

reactjs - 记录 setState 调用

javascript - 从内部页面隐藏横幅 - magento

javascript - 停止或终止 Node 媒体服务器

javascript - 在 md-button 上应用图标样式

javascript - 为什么我的代码按照它的顺序执行