首页 > 解决方案 > 反应状态未设置为仅对象中的一个键

问题描述

我真的不知道如何解释这一点。

我的网站上有一个个人资料页面 ( /profile),它访问 API ( /api/testAPI/currentuser.php)

currentuser.php返回以下 JSON -{loggedin: true, uid: "3", username: "TechPhil", permissions: "none"}

在我的反应组件中,我componentDidMount()使用以下函数在阶段中获取此端点

fetch("/api/testAPI/currentuser.php")
        .then((res) => res.json())
        .then((res) => {
          this.setState({
            apiResponse: res
          })
        })

不要问我为什么,但是我可以使用uid,usernamepermissions键很好地访问this.state.apiResponse.key,但是由于某种原因我根本无法访问loggedin

我已将完整的组件代码放在下面。

import React, {Component} from 'react'
import {Redirect, Link} from 'react-router-dom'

class ProfilePage extends Component {
    constructor(props) {
        super(props);
        this.state = {apiResponse:{}};
      }
    
      getUser(){
        fetch("/api/testAPI/currentuser.php")
        .then((res) => res.json())
        .then((res) => {
          this.setState({
            apiResponse: res
          })
        })
          
      }
    
      componentDidMount() {
        this.getUser();
      }

      render() {
        if (this.state.apiResponse.loggedin){
          return(
            <div className="container">
                <h2>Your Profile</h2>
                <p>User ID: {this.state.apiResponse.uid}</p>
                <p>Username: {this.state.apiResponse.username}</p>
                <p>Permissions: {this.state.apiResponse.permissions}</p>
                <Link to="/profile/changepw">Change your Password</Link>
            </div>
         ) 
        } else {
          return(<Redirect to="/login"/>)
        }
      }
}

export default ProfilePage

标签: javascriptreactjs

解决方案


推荐阅读