首页 > 解决方案 > this.state 未在 html 中显示

问题描述

很可能我做错了,当我 console.log this.state.name 并通过电子邮件发送它时,它会显示在控制台中,但是当我渲染它时它不会出现。我很陌生,所以请原谅代码,如果有更好的方法,请告诉我。我在这里尝试做的是从 axios.get 请求(profilePage)中获取个人资料页面并在页面上显示此数据

import React, { Component } from 'react';
import { profilePage } from '../UserFunctions'

export default class Profile extends Component {
    constructor() {
      super();
      //Set default message
      this.state = {
        param: null,
        message: 'Loading...',
        name: '',
        email: ''
      }
    } 

    componentDidMount() {
      let Paramvalue=this.props.match.params.id;
      this.state.param = Paramvalue

      var user = this.state.param
      profilePage(user).then(res => {
        this.state.name = res.data[0].fname + ' ' + res.data[0].lname
        this.state.email = res.data[0].email
        console.log(this.state.name)
      })

    }
    render() {
      return (
        <div>
          <h1>Home</h1>
          <h1>{this.state.name}</h1>
          <h1>{this.state.email}</h1>
        </div>
      );
    }
  }

标签: reactjsreact-router

解决方案


这是因为您直接改变状态对象而不是调用setState,因此不会触发重新渲染。这是您的代码的修改版本,应该可以按预期工作。

import React, { Component } from 'react';
import { profilePage } from '../UserFunctions'

export default class Profile extends Component {
    constructor() {
      super();
      //Set default message
      this.state = {
        param: null,
        message: 'Loading...',
        name: '',
        email: ''
      }
    } 

    componentDidMount() {
      let user=this.props.match.params.id;
      profilePage(user).then(res => {
        this.setState({
          name: res.data[0].fname + ' ' + res.data[0].lname,
          email: res.data[0].email,
          param: user,
        });
      })

    }
    render() {
      return (
        <div>
          <h1>Home</h1>
          <h1>{this.state.name}</h1>
          <h1>{this.state.email}</h1>
        </div>
      );
  }
}

推荐阅读