TypeError: Cannot read property 'setState' of undefined in child to parent component
TypeError: Cannot read property 'setState' of undefined in child to parent component
我收到以下错误。
TypeError: Cannot read property 'setState' of undefined
closeAlert
好像是绑定或者道具的问题?
那我该怎么办?
主要成分:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
alertOpen : false
};
this.closeAlert.bind(this);
}
closeAlert(event) {
this.setState({
closeAlert : true
});
}
render() {
return (
<div>
<AlertWindow
closeAlert={this.closeAlert}
/>
</div>
);
}
}
子组件:
const AlertWindow = ({ closeAlert }) => {
return (
<Alert type="primary">
<Button
color="secondary"
RootComponent="button"
onClick={(event) => {
closeAlert(event)
}}
>
No, thanks
</Button>
</Button.List>
</Alert>
);
};
你的绑定语句不正确,改成如下:
this.closeAlert = this.closeAlert.bind(this);
您需要将绑定函数赋值给class方法。没有分配的绑定是不够的。
希望对您有所帮助!
我认为您对命名有点困惑。您正在设置 alertOpen
状态。
不太确定 AlertWindow
的作用,但您需要一个调用 closeAction 的操作(如 onClick={this.closeAlert}
)
正如@Alexander 提到的,您的绑定不正确。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
alertOpen : true
};
this.closeAlert = this.closeAlert.bind(this);
}
closeAlert(event) {
this.setState({
alertOpen : false
});
}
render() {
return (
<AlertWindow
closeAlert={this.state.closeAlert}
/>
);
}
}
你的 'opens' 和 'closes' 混淆了,所以我不知道初始状态应该是什么。
另一个简单的解决方法:
将您的 cloaseAlert 方法转换为:
closeAlert=(event)=> {
this.setState({
closeAlert : true
});
}
现在您不需要构造函数中方法的绑定语句
我收到以下错误。
TypeError: Cannot read property 'setState' of undefined
closeAlert
好像是绑定或者道具的问题?
那我该怎么办?
主要成分:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
alertOpen : false
};
this.closeAlert.bind(this);
}
closeAlert(event) {
this.setState({
closeAlert : true
});
}
render() {
return (
<div>
<AlertWindow
closeAlert={this.closeAlert}
/>
</div>
);
}
}
子组件:
const AlertWindow = ({ closeAlert }) => {
return (
<Alert type="primary">
<Button
color="secondary"
RootComponent="button"
onClick={(event) => {
closeAlert(event)
}}
>
No, thanks
</Button>
</Button.List>
</Alert>
);
};
你的绑定语句不正确,改成如下:
this.closeAlert = this.closeAlert.bind(this);
您需要将绑定函数赋值给class方法。没有分配的绑定是不够的。
希望对您有所帮助!
我认为您对命名有点困惑。您正在设置 alertOpen
状态。
不太确定 AlertWindow
的作用,但您需要一个调用 closeAction 的操作(如 onClick={this.closeAlert}
)
正如@Alexander 提到的,您的绑定不正确。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
alertOpen : true
};
this.closeAlert = this.closeAlert.bind(this);
}
closeAlert(event) {
this.setState({
alertOpen : false
});
}
render() {
return (
<AlertWindow
closeAlert={this.state.closeAlert}
/>
);
}
}
你的 'opens' 和 'closes' 混淆了,所以我不知道初始状态应该是什么。
另一个简单的解决方法: 将您的 cloaseAlert 方法转换为:
closeAlert=(event)=> {
this.setState({
closeAlert : true
});
}
现在您不需要构造函数中方法的绑定语句