Javascript SetState不是OnChange上的函数
正在获取滑块以更改处于React状态的文本值 不断出现错误: App.js:90 Uncaught TypeError:this.setState不是一个函数,尽管我尽了最大努力进行了故障排除 解决办法是什么Javascript SetState不是OnChange上的函数,javascript,reactjs,state,onchange,setstate,Javascript,Reactjs,State,Onchange,Setstate,正在获取滑块以更改处于React状态的文本值 不断出现错误: App.js:90 Uncaught TypeError:this.setState不是一个函数,尽管我尽了最大努力进行了故障排除 解决办法是什么 class App extends Component { constructor(props) { super(props); this.state = {list: [{x: "Before Pool", y:85000}, {x: "After Poo
class App extends Component {
constructor(props) {
super(props);
this.state = {list: [{x: "Before Pool", y:85000}, {x: "After Pool", y:82000}], text: 0, options: {bathrooms:'', bedrooms:'', sqft:''}};
}
componentDidMount() {
setTimeout(() => {
this.setState({list: [{x: "Before Pool", y:60000}, {x: "After Pool", y:30000}]});
console.log("testing", this.state.text);
}, 2000) ;
}
handleChange (event) {
console.log("from handle change", event);
this.setState({text : event });
}
render() {
return (
<div className="App">
<div>
<div style={wrapperStyle}>
<p># of Bathrooms</p>
<Slider min={0} max={20} defaultValue={3} onChange={this.handleChange} />
</div>
您需要绑定handleChange方法
您需要绑定handleChange方法
您需要在setTimeout内将状态绑定到回调,因为您处于不同的上下文中。 我相信这会奏效:
setTimeout(() => {
this.setState({list: [{x: "Before Pool", y:60000}, {x: "After Pool", y:30000}]});
console.log("testing", this.state.text);
}.bind(this), 2000) ;
您需要在setTimeout内将状态绑定到回调,因为您处于不同的上下文中。 我相信这会奏效:
setTimeout(() => {
this.setState({list: [{x: "Before Pool", y:60000}, {x: "After Pool", y:30000}]});
console.log("testing", this.state.text);
}.bind(this), 2000) ;
答案很简单:今年你看错了方向 因为您在闭包中编写回调,所以重要的是要知道您不能从外部访问this。它总是指当前上下文 作为一种解决方法,请定义自己的变量(通常称为self),以便在闭包内使用: 组件安装{ var self=this;//复制引用 设置超时=>{ self.setState{list:[{x:prefore Pool,y:60000},{x:After Pool,y:30000}]; console.logtesting,this.state.text; }, 2000 ; }
答案很简单:今年你看错了方向 因为您在闭包中编写回调,所以重要的是要知道您不能从外部访问this。它总是指当前上下文 作为一种解决方法,请定义自己的变量(通常称为self),以便在闭包内使用: 组件安装{ var self=this;//复制引用 设置超时=>{ self.setState{list:[{x:prefore Pool,y:60000},{x:After Pool,y:30000}]; console.logtesting,this.state.text; }, 2000 ; } 您需要在此处绑定HandleChange方法
<Slider min={0} max={20} defaultValue={3} onChange={this.handleChange} />
您需要在此处绑定HandleChange方法
<Slider min={0} max={20} defaultValue={3} onChange={this.handleChange} />
谢谢你,马里奥!你的回答与另外两个答案相呼应——非常好的分析。感谢@Mario!你的答案与其他两个答案相呼应——很棒的分析。你能把我的答案标记为正确答案,这样其他人就可以从中得到帮助吗?你能把我的答案标记为正确答案,这样其他人就可以从中得到帮助吗?很高兴听到这个消息,如果你的问题完全解决了,那么你接受一个答案,向其他用户表明这一点,对你有帮助。当然,它不需要是我的,但是如果你接受了它,那会很有帮助。很高兴听到这个消息,如果你的问题完全解决了,那么你接受一个答案来向其他用户表明这一点会很有帮助。当然,它不需要是我的,但是如果你接受了它,它会很有帮助。
handleChange = event => {
console.log("from handle change", event);
this.setState({text : event });
}