我无法在父状态下更新filterTimeframe。它正在改变filterDate罚款。我没有包含代码,但是datePickerApply从DatePicker库中获取值。第二个setTimeframe是一个select下拉列表中的onChange。两者都在子组件中。
更新:我为“父代”粘贴了错误的代码。
class Child extends React.Component {
constructor(props) {
super(props);
this.state = null;
this.datePickerApply = this.datePickerApply.bind(this);
this.setTimeframe = this.setTimeframe.bind(this);
}
datePickerApply(event, picker) {
if (typeof this.props.setDate === 'function') {
this.props.setDate(picker.startDate.format('YYYY-MM-DD'));
}
}
setTimeframe(event) {
if (typeof this.props.setTimeframe === 'function') {
this.props.setTimeframe(event.target.value);
}
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
filterDate: [],
filterTimeframe: [],
}
}
setDate = (filterDate) => {
this.setState((state) => {
return {filterDate: filterDate}
});
console.log(this.state.filterDate)
}
setTimeframe = (filterTimeframe) => {
this.setState((state) => {
return {filterTimeframe: filterTimeframe}
});
console.log(this.state.filterTimeframe)
}
render() {
return (
<div className="container">
<div className="container-fluid" id="main-header">
<Child filterDate={this.state.filterDate} filterTimeframe={this.state.filterTimeframe} setDate={this.setDate} setTimeframe={this.setTimeframe}} />
</div>
</div>
);
}
}
答案 0 :(得分:0)
您将console.log
放在错误的位置。 setState
函数是异步的。要了解更多信息,请访问:https://stackoverflow.com/a/40408976/11285186
setDate = (filterDate) => {
this.setState((state) => {
return {filterDate: filterDate}
}, () => {
console.log(this.state.filterDate);
});
}
setTimeframe = (filterTimeframe) => {
this.setState((state) => {
return {filterTimeframe: filterTimeframe}
}), () => {
console.log(this.state.filterTimeframe);
});
}