我在isCorrectAnsweraxios 呼叫中為變數設定狀態時遇到了麻煩。我Cannot read properties of undefined (reading 'setState')在控制臺日志中收到錯誤。我究竟做錯了什么?isCorrectAnswer變數的初始狀態是 constructor(props) {super(props)this.state = { isCorrectAnswer: false }}
和 axios 呼叫是
axios.post(
"API/path/to/ressource",
postData,
{
headers: {
"X-Access-Token":
"token",
},
}
)
.then(function (res) {
this.setState({
isCorrectAnswer: res.data.correct //Here im trying to change the state
}, () => console.log(this.state.isCorrectAnswer)) //and logging into console
})
.catch(function (error) {
console.log(error);
});
uj5u.com熱心網友回復:
當你呼叫一個函式(非箭頭函式)時,this總是一個隱式引數。
正常功能
我所說的普通函式是指不是方法的函式。
在嚴格模式下,值this總是undefined。
在非嚴格模式下,值this始終是全域物件(window在瀏覽器中)
顯示代碼片段
function foo() {
"use strict";
return this;
}
function bar() {
return this;
}
console.log(foo() === undefined); // true
console.log(bar() === window); // true
方法
this指呼叫該方法的物件。
顯示代碼片段
function foo() {
"use strict";
return this;
}
const obj = { foo };
console.log(obj.foo() === obj); // true
在你的情況下,傳遞給的回呼then是一個普通函式(不是方法),所以它this是 set undefined,因此你得到一個錯誤。
更新到箭頭函式,它會解決這個問題,因為箭頭函式沒有自己的this,箭頭函式this是根據詞法范圍決定的。查看以下示例:
const getRandomNums = (delay) =>
new Promise((res) => setTimeout(() => res([5, 2, 3]), delay));
class App extends React.Component {
constructor() {
super();
this.state = { nums: [] };
}
componentDidMount() {
getRandomNums(1500).then((nums) => {
this.setState({ nums });
});
}
render() {
return <div>{JSON.stringify(this.state.nums, null, 2)}</div>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
uj5u.com熱心網友回復:
您也可以使用箭頭功能代替function
axios.post(
"API/path/to/ressource",
postData,
{
headers: {
"X-Access-Token":
"token",
},
}
)
.then((res) => {
this.setState({
isCorrectAnswer: res.data.correct //Here im trying to change the state
}, () => console.log(this.state.isCorrectAnswer)) //and logging into console
})
.catch((error) => {
console.log(error);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466113.html
