Javascript React JS未捕获引用错误:未定义函数
我正在尝试调用shuffleCards,当在ReactJs组件中单击事件时。但是,我收到以下错误:Javascript React JS未捕获引用错误:未定义函数,javascript,reactjs,Javascript,Reactjs,我正在尝试调用shuffleCards,当在ReactJs组件中单击事件时。但是,我收到以下错误: Uncaught ReferenceError: shuffleCards is not defined 这是我的密码: constructor(props) { super(props); this.state = { count: 0 }; } shuffleCards(array) { var i = array.length,
Uncaught ReferenceError: shuffleCards is not defined
这是我的密码:
constructor(props) {
super(props);
this.state = {
count: 0
};
}
shuffleCards(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
handleClickEvent(event) {
var cards = [
{txt: "A",
isDisplayed: false},
{txt: "B",
isDisplayed: false},
{txt: "C",
isDisplayed: false}
];
if (this.state.count == 0) {
cards = shuffleCards(cards);
}
}
这对你有用吗?此处演示: 在
handleClickEvent
方法中引用shuffleCards
时,您错过了this
shuffleCards(array) {
// logic here
}
handleClickEvent(event) {
cards = this.shuffleCards(cards);
}
render() {
return (
<button onClick={this.handleClickEvent.bind(this)}>Click me</button>
);
}
shuffleCards(数组){
//这里的逻辑
}
handleClickEvent(事件){
卡片=这个。shuffleCards(卡片);
}
render(){
返回(
点击我
);
}
EDIT刚刚看到了评论,而且zerkms已经为您提供了解决方案。为了澄清起见,我将留下我的答案
您的问题是在
handleclick方法
中,您调用的是shuffleCards
,而不是this.shuffleCards
shuffleCards(array) {
// ...
}
handleClickEvent(event) {
// ...
if (this.state.count == 0) {
cards = this.shuffleCards(cards); // here you should use `this.`
}
}
原因是组件上定义了shuffleCards
方法,可以通过this
属性从其方法访问该方法
如果在handleClickMethod
中定义了shuffleCards
,则可以调用它而无需访问this
:
handleClickEvent(event) {
function shuffleCards(array) {
// ...
}
// ...
if (this.state.count == 0) {
cards = shuffleCards(cards); // here you don't need `this.`
}
}
我也有同样的问题 我升级了“react scripts”并解决了这个问题 也许我能解决这个问题
npm i react-scripts
this.shuffleCards
@zerkms哇,真不敢相信我没有想到要这么做。成功了。谢谢