Reactjs 如何在componentDidMount()方法中使用this.setState将响应设置为状态
从我的react应用程序中,我向SpringMVC控制器发出了一个Ajax请求,从请求的spring控制器得到了一个Jason响应 现在,我试图在我的Reactjs 如何在componentDidMount()方法中使用this.setState将响应设置为状态,reactjs,Reactjs,从我的react应用程序中,我向SpringMVC控制器发出了一个Ajax请求,从请求的spring控制器得到了一个Jason响应 现在,我试图在我的componentDidMont()中使用react js将此响应设置为构造函数中使用this.setState方法定义的状态 当我尝试使用this.setState方法设置状态时,我得到类型错误: 无法读取未定义错误的属性“set State” 请帮我修复这个错误 Course.js 渲染方法 render(){ 返回( 响应-{this.sta
componentDidMont()
中使用react js将此响应设置为构造函数中使用this.setState
方法定义的状态
当我尝试使用this.setState
方法设置状态时,我得到类型错误:
无法读取未定义错误的属性“set State”
请帮我修复这个错误
Course.js
渲染方法
render(){
返回(
响应-{this.state.items};
);
} }
以下是错误消息:
在Javascript中,定义匿名
函数
不会自动从上层范围继承此
上下文。因此,当您为ajax请求定义一个匿名函数
回调时,这个
在其内部变成了未定义的
。由于您已经在使用ES6功能(如导入和类),因此也可以使用with=>
来解决此问题。它们的行为类似于普通函数,但不会创建新的上下文。因此,您只需在组件didmount
中执行此操作:
axios.get('http://localhost:8080/ulearn/rest/course/getAll')
。然后((响应)=>{
this.setState({items:response});
控制台日志(响应);
}).catch((错误)=>{
console.log(错误);
});
根据您评论中的错误,因为我上面的回答击败了我,无法回答您的问题:)-
如果要打印整个对象,请尝试单独打印每个项目,或在渲染方法中的this.state.items
后面添加.toString()
。当您尝试打印new Date()
时也会发生同样的情况,例如,它不允许您打印整个对象,但允许您打印对象的字符串表示形式,因此new Date().toString()
将起到例如的作用。{object.keys(this.state.items).map(function(key){return Key:{Key},Value:{this.state.items[Key]};}}}当我尝试使用上述给定代码迭代对象时,我得到了TypeError:无法读取未定义(…)的属性“state”如何修复此问题???@VijayRNair您需要在那里执行相同的操作,将函数
定义替换为箭头:Object.keys(this.state.items).map((key)=>{return key:{key},Value:{this.state.items[key]};})
。错误:对象作为React子对象无效(找到:具有键的对象{指令、数据、状态、消息})。如果要呈现子对象的集合,请改用数组,或使用React加载项中的createFragment(object)包装对象。请检查课程的呈现方法(…)当我尝试使用上述给定代码迭代对象时,出现TypeError:无法读取未定义(…)的属性“state”这里发生的事情与第一个问题相同,您在一个匿名函数(映射函数)中,该函数对此的引用不正确。请尝试:Object.keys(this.state.items)。map((key)=>{return key:{key},Value:{this.state.items[key]})。bind(this)}
my render method render(){const{query}=this.props.location;const{params}=this.props;const{article}=params;const{date,filter}=query;return(Object.keys(this.state.items).map((key)=>{返回键:{Key},值:{this.state.items[Key]}.bind(this)};}
import React from "react";
import Article from "../components/Article";
import axios from 'axios';
export default class Courses extends React.Component {
constructor() {
super();
this.state={items:[]};
}
componentDidMount() {
console.log("hello");
axios.get('http://localhost:8080/ulearn/rest/course/getAll').then(function (response) {
this.setState({items: response});
console.log(response);
}).catch(function (error) {
console.log(error);
});
}
render() {
return (
<div>
<div>Response - {this.state.items}</div>;
</div>
);
} }