![](/img/trans.png)
[英]trying to set new state with function in componentDidMount: this.setState is not a function
[英]How to Set the response to a state by using this.setState inside a componentDidMount() method
在我的react應用程序中,我向spring Mvc控制器發出了Ajax請求,並從所請求的spring控制器中獲得了Jason響應。
現在,我嘗試使用react js將我的componentDidMont ()
中的此響應設置為使用this.setState
方法在構造函數中定義的狀態。
當我嘗試使用this.setState
方法設置狀態時, this.setState
類型錯誤:
無法讀取未定義錯誤的屬性“設置狀態”
請幫我解決此錯誤。
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>
);
} }
下面是錯誤消息:
在Javascript中,定義匿名function
不會自動從較高范圍繼承this
上下文。 因此,當您為ajax請求定義匿名function
回調時, this
回調在其內部變得undefined
。 由於您已經在使用ES6功能(例如導入和類),因此還可以將箭頭功能與=>
一起使用以解決此問題。 它們的行為類似於正常函數,但不會創建新的this
上下文。 因此,您只需在componentDidMount
執行以下操作:
axios.get('http://localhost:8080/ulearn/rest/course/getAll')
.then((response) => {
this.setState({items: response});
console.log(response);
}).catch((error) => {
console.log(error);
});
根據您評論中的錯誤,正如我上面的回答使我無法回答您的問題:)-
您試圖打印出整個對象,嘗試分別打印出每個項目,或者在render方法中的this.state.items
后面添加.toString()
。 例如,當您嘗試打印new Date()
,會發生相同的事情,它不會讓您打印出整個對象,但是它將使您打印對象的字符串表示形式,因此new Date().toString()
例如會工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.