reactjs - 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>
);
}
}
解决方案
这是因为您直接改变状态对象而不是调用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>
);
}
}
推荐阅读
- json - Reactjs中如何通过嵌套对象获取值
- java - 获取JDBC连接失败;嵌套异常是 java.sql.SQLException: null
- azure - 在 Azure SQL 数据仓库中创建外部表
- google-cloud-platform - 除了 Prometheus,还有哪些 Metrics Providers 可以与 ArgoCD 一起使用?
- reactjs - 在 useContext 中使用 useReducer
- join - 时间窗口连接以在 flink 中的固定大小翻滚窗口上聚合数据
- java - SpringBoot 和 AngularJs - 在 Intellij 中更新修改的静态文件 (js/html/css)
- javascript - 如何使用 LocalStorage 值来保存按钮的特定背景颜色?
- php - php - 使用正则表达式从数组中删除键和值
- r - 当 drop = FALSE 时,ggplot2 警告“删除了包含缺失值的 x 行”