由于某种原因,我的setState没有更新...我的回调函数甚至没有触发。我尝试将函数onSubmit()
定义为onSubmit()
而不是onSubmit = () =>
。有任何想法吗?是的,我已经验证了我的if (milestoneBtnLabel === "Create")
正在执行。
constructor(props) {
super(props);
this.state = {
campus: []
};
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit = e => {
const { milestoneBtnLabel, schoolData } = this.props;
e.preventDefault();
if (milestoneBtnLabel === "Create") {
this.setState(
{
campus: this.state.campus.concat(schoolData.schoolData.name)
},
() => {
console.log("here"); <-- Doesn't execute
this.props.saveChecklistItem({ ...this.state });
}
);
}
this.props.closeModal();
};
答案 0 :(得分:1)
也许this.props.closeModal();
在setState()
完成之前从DOM中删除了该组件。尝试将该呼叫移至setState
回调中。
if (milestoneBtnLabel === "Create") {
this.setState(
{
campus: this.state.campus.concat(schoolData.schoolData.name)
},
() => {
console.log("here"); <-- Doesn't execute
this.props.saveChecklistItem({ ...this.state });
this.props.closeModal();
}
);
else {
this.props.closeModal();
}
答案 1 :(得分:0)
您的代码中有几件事需要更正
更改
onSubmit = e => {
const { milestoneBtnLabel, schoolData } = this.props;
e.preventDefault();
if (milestoneBtnLabel === "Create") {
this.setState(
{
campus: this.state.campus.concat(schoolData.schoolData.name)
},
() => {
console.log("here"); <-- Doesn't execute
this.props.saveChecklistItem({ ...this.state });
}
);
}
this.props.closeModal();
}
收件人
onSubmit = e => {
const { milestoneBtnLabel, schoolData, closeModal, saveChecklistItem} = this.props;
e.preventDefault();
if (milestoneBtnLabel === "Create" && schoolData && schoolData.schoolData){
this.setState( prevState => (
{
campus: [...prevState.campus, schoolData.schoolData.name]
}),
() => {
console.log("here"); <-- Doesn't execute
saveChecklistItem({ ...this.state });
}
);
}
setTimeout(()=>{
closeModal();
}, 2000);
}