Reactjs 此.state未在html中显示
很可能是我做错了,当我使用console.log this.state.name和email时,它会显示在控制台中,但当我渲染时它不会显示。我是新手,所以请原谅代码,如果有更好的方法,请告诉我。我在这里试图做的是从axios.get请求(profilePage)中获取配置文件页面,并在页面上显示这些数据Reactjs 此.state未在html中显示,reactjs,react-router,Reactjs,React Router,很可能是我做错了,当我使用console.log this.state.name和email时,它会显示在控制台中,但当我渲染时它不会显示。我是新手,所以请原谅代码,如果有更好的方法,请告诉我。我在这里试图做的是从axios.get请求(profilePage)中获取配置文件页面,并在页面上显示这些数据 import React, { Component } from 'react'; import { profilePage } from '../UserFunctions' export
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>
);
}
}
import React,{Component}来自'React';
从“../UserFunctions”导入{profilePage}
导出默认类配置文件扩展组件{
构造函数(){
超级();
//设置默认消息
此.state={
参数:null,
消息:“正在加载…”,
名称:“”,
电子邮件:“”
}
}
componentDidMount(){
让Paramvalue=this.props.match.params.id;
this.state.param=Paramvalue
var user=this.state.param
profilePage(用户)。然后(res=>{
this.state.name=res.data[0]。fname+''+res.data[0]。lname
this.state.email=res.data[0]。电子邮件
console.log(this.state.name)
})
}
render(){
返回(
家
{this.state.name}
{this.state.email}
);
}
}
这是因为您直接改变状态对象,而不是调用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>
);
}
}
import React,{Component}来自'React';
从“../UserFunctions”导入{profilePage}
导出默认类配置文件扩展组件{
构造函数(){
超级();
//设置默认消息
此.state={
参数:null,
消息:“正在加载…”,
名称:“”,
电子邮件:“”
}
}
componentDidMount(){
让user=this.props.match.params.id;
profilePage(用户)。然后(res=>{
这是我的国家({
名称:res.data[0]。fname+“”+res.data[0]。lname,
电子邮件:res.data[0]。电子邮件,
参数:用户,
});
})
}
render(){
返回(
家
{this.state.name}
{this.state.email}
);
}
}
react中有一个很大的禁忌:永远不要直接改变状态。使用setState