![](/img/trans.png)
[英]React.js - TypeError: Cannot read property 'catch' of undefined
[英]Cannot read property 'bind' of undefined, React.js
當它綁定到我的addTimes函數時,我得到一個錯誤說明:無法讀取undefined的屬性'bind'。
我在ReactjJS和Webpack中構建。 我最近有另一個問題,人們建議:
this.addTimes = this.addTimes.bind(this);
請參閱: 無法讀取未定義的ReactJS的屬性“setState”
class Settings extends React.Component {
constructor(props) {
super(props);
this.state = {
times: []
};
}
render(){
this.addTimes = this.addTimes.bind(this);
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
var currentTicked = [];
var times =[]
function addTimes(id){
var index = times.indexOf(id);
if (!times.includes(id)) {
$("input:checkbox[name=time]:checked").each(function(){
currentTicked.push($(this).val());
times = times.concat(currentTicked)
times = jQuery.unique(times);
currentTicked = [];
});
} else if(times.includes(id)){
times = times.remove(id);
}
console.log(times);
this.setState = {
thims: times
}
}
為了能夠綁定addTimes
到this
在構造函數中, addTimes
必須在你的類中的方法,不只是在渲染方法的功能。
class Settings extends React.Component {
constructor(props) {
super(props);
this.state = {
times: []
};
this.addTimes = this.addTimes.bind(this);
}
addTimes(id) {
// ...
}
}
如果你想創建addTimes
的渲染方法,你可以只綁定this
到功能有:
function addTimes(id) {
// ...
}.bind(this);
或者你可以把它改成箭頭功能:
const addTimes = (id) => {
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.