首页 > 解决方案 > React + Laravel - 未定义设置状态

问题描述

我正在尝试打印从 API 获取的值。数据来了但无法设置状态

尝试了一切

反应.js

import React, { Component } from 'react'
import axios from 'axios'

class Admin extends Component {
constructor(props) {
    super(props)    
    this.state = {
         users:  []
    }
}
componentDidMount(){
    axios.get('/api/adminUsers')
        .then(response =>{      
            this.setState({users: response.data})
            console.log(response.data)
            console.log(this.setState({users: response.data}))
        })
        .catch(error=>{
            this.setState({ errorMsg: "Something is wrong here"})
            console.log(error)
        })
}

render() {
    const{users} = this.state
    <div>

{
  users.length ?
  users.map(user => <div key= 
  {user.id}>{user.name}</div>)
  : null
}

        </div>  
     )
  }
}

export default Admin

控制台中显示的 response.data 是:

{[
created_at: "2019-08-31 14:06:29"
email: "amit.khare588@gmail.com5"
email_verified_at: null
id: 2
name: "Amit Khare"
role: "Doctor"
updated_at: "2019-08-31 14:06:29"
]}

我只想把数据打印回来

标签: reactjslaravel

解决方案


下面的代码看起来很好是一个完整的工作示例:

import React from "react";
import ReactDOM from "react-dom";


class Admin extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            users: [],
            errorMsg: ''
        }
    }

    componentDidMount() {
        axios.get('/api/adminUsers')
            .then(response => {
                this.setState({users: response.data.users})
                console.log(response.data)
            })
            .catch(error => {
                this.setState({errorMsg: "Something is wrong here"})
                console.log(error)
            })
    }

    render() {
        const {users, errorMsg} = this.state;

        return <div>
            {users.length ? users.map(user => <div key={user.id}>{user.name}</div>) : null}
            {errorMsg ? <div>{errorMsg}</div> : null}
        </div>
    }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Admin/>, rootElement);

查看代码框: https ://codesandbox.io/s/nice-fermi-ku1jr


推荐阅读