gpt4 book ai didi

javascript - ReactJS 只能设置状态不能获取状态

转载 作者:行者123 更新时间:2023-11-30 15:03:45 24 4
gpt4 key购买 nike

在 ReactJS 中,我成功地将 props 从父组件传递给子组件,但是当回调函数被调用时,我注意到

  1. this.setState() 之后的行没有被执行。
  2. this.state.* 的值根本无法访问。

有人可以帮忙吗?

class RealTime extends Component {
constructor() {
super();
this.state = {
mode: true,
marker_name: '',
sensor_id: ''
};
}

handleInputChange(event) {
if(event.target.type === 'checkbox') {
alert("checked = " + event.target.checked);
this.setState({
mode: event.target.checked
});
alert("yy");
}
else if(event.target.type === 'text') {
alert("event.target.name = " + event.target.name + " value = " + event.target.value);
this.setState({
[event.target.name]: event.target.value
});
}
else {
alert("Unknown input type = " + event.target.type);
}

alert("xx");
}

handleSubmit(event) {
event.preventDefault();
alert('handleSubmit');
alert("submitted marker_name=" + this.state.mode);
}

render() {
return (
<div className="animated fadeIn">
<Row>
<Col xs="12">
<Card>
<CardHeader>
Real Time Number of Customers in Shops
</CardHeader>
<CardBlock className="card-body">
<MarkerForm mode={this.state.mode} marker_name={this.state.marker_name} sensor_id={this.state.sensor_id}
handleInputChange={this.handleInputChange} handleSubmit={this.handleSubmit}/>
<ConsoleEvent/>
<Canvas/>
</CardBlock>
</Card>
</Col>
</Row>
</div>
)
}
}

class MarkerForm extends Component {
render() {
return (
<Form inline onSubmit={this.props.handleSubmit}>
<FormGroup>
<Label className="switch switch-text switch-success switch-lg">
<Input type="checkbox" className="switch-input" checked={this.props.mode} onChange={this.props.handleInputChange}/>
<span className="switch-label" data-on="On" data-off="Off"></span>
<span className="switch-handle"></span>
</Label>
</FormGroup>
<FormGroup>
<Input type="text" placeholder="Marker Name" name="marker_name" value={this.props.marker_name} onChange={this.props.handleInputChange} required/>
</FormGroup>
<FormGroup>
<Input type="text" placeholder="Sensor ID" name="sensor_id" value={this.props.sensor_id} onChange={this.props.handleInputChange} required/>
</FormGroup>
<FormGroup className="form-actions">
<Button type="submit" color="primary" id="add-marker"><i className="fa fa-plus-square"></i> Add Marker</Button>
<Button type="button" color="danger" id="remove-marker"><i className="fa fa-minus-square"></i> Remove Marker</Button>
</FormGroup>
</Form>
)
}
}

在上面的代码中,

alert("yy") 永远不会被执行。 alert("xx") 也不是。这是在 handleInput 中。

handleSubmit() 中,我只能看到警告框“handleSubmit”,但看不到“submitted marker_name=

最佳答案

您应该绑定(bind) 函数。这是因为 this 在没有绑定(bind)的情况下有不同的上下文:

constructor() {
super();
this.state = {
mode: true,
marker_name: '',
sensor_id: ''
};

this.handleSubmit = this.handleSubmit.bind(this)
}

关于javascript - ReactJS 只能设置状态不能获取状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46117647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com