【发布时间】:2019-10-17 19:32:10
【问题描述】:
我在渲染函数中映射了一个包含 opening_hours 的列表。我将它们映射到子组件。当子组件状态发生更改时,我想更改父状态中每个对象的值。唯一的问题是我的值在子组件和父状态中都没有改变。我已经将onChange方法传递给每个子组件,但问题在于我的onChange函数在父状态下。
我尝试将 onChange 传递给我的子组件并使用 [e.target.name] 更新状态:e.target.value。但这没有用。所以我尝试复制arrayList并根据映射arrayList的索引更新状态。那也没用。
handleOnChange = (index) => {
let newData = [...this.state.opening_hours];
this.setState(
newData.map((barbershop, j) => {
if (j === index) {
return barbershop;
console.log(barbershop)
}
return {
newData,
};
}));
console.log(newData)
};
render() {
return (
<>
<div className="container mb-2">
<h4>Opening hours </h4>
<Form>
{this.state.opening_hours.map((barbershop, index) => (
<Day
key={barbershop.id}
day={barbershop.day}
open_time={barbershop.open_time}
close_time={barbershop.close_time}
index = {index}
onChange={() => this.handleOnChange(index)}/>
))}
</Form>
<Button onClick={this.handleSubmit} variant="primary" type="submit">
Update opening hours
</Button>
</div>
</>
);
}
}
我的子组件是这样的
class Day extends Component {
constructor(props) {
super(props);
this.state = {
day: this.props.day,
open_time: this.props.open_time,
close_time: this.props.close_time,
};
console.log(this.state)
}
handleChange = () => {
this.props.onChange(this.props.index)
}
render() {
return (
<Form.Group as={Row}>
<Form.Label column sm="3">
{ENUM[this.state.day]}
</Form.Label>
<Col sm="3">
<Form.Control
name="open_time"
value={this.state.open_time}
onChange={this.handleChange}
type="time"
min="08:00"
max="24:00"/>
</Col>
<Col sm="3">
<Form.Control
name="close_time"
value={this.state.close_time}
onChange={this.handleChange}
type="time"
min="08:00"
max="24:00"/>
</Col>
</Form.Group>
);
}
}
编辑:
【问题讨论】:
标签: javascript arrays reactjs components