这个问题在这里已有答案:
我想完成以下任务:
myFunction = () => {
this.setState(
state => {
const originalBar = state.bar;
return {
foo: "bar"
};
},
() => ({ originalBar, newBar: state.foo }) //return this object
);
};
otherFunction = () => {
var originalValue = myFunction(); //access returned object (in child component)
};
setState不会返回任何内容,我想知道如何执行此操作的唯一方法是在setState回调中调用my function
的回调,但是,如果可能的话,我更喜欢使用异步等待。
你可以从Promise
返回一个新的myFunction
,它在回调中被解析为setState
。
然后你可以在你的async
中使用await
/ otherFunction
。
myFunction = () => {
return new Promise(resolve => {
let originalFoo;
this.setState(
state => {
originalFoo = state.foo;
return {
foo: "bar"
};
},
() => resolve({ originalFoo, newFoo: this.state.foo })
);
});
};
otherFunction = async () => {
var originalValue = await myFunction();
};
我在下面的实现不使用async / await。如果你需要等到setState
完成,你可能会更好地接受Tholle的回答。但是,如果您只是想要返回一个具有值的对象,而不管状态是否已完全设置,那么我的有点清洁。
myFunction = () => {
let returnData;
this.setState(state => {
// do some stuff here
returnData = { originalBar, newBar: state.foo };
return {
foo: "bar"
};
});
return returnData;
}
otherFunction = () => {
var originalValue = this.myFunction();
}
但是,我不推荐这个,而是我会尽量不在this.setState
中使用函数回调。
也许你可以做这样的事情?
const originalBar = this.state.foo; // or whatever it might be
const newBar = "bar";
this.setState({ foo: newBar });
return { originalBar, newBar };
相当短,而且更优雅。
看起来你想要访问以前的状态和当前状态。不是使用setState
做一些不适合它的事情,你可以使用生命周期方法,根据你的用例提供先前的状态以及之前的道具。
componentDidUpdate(prevProps, prevState, snapshot){
...
}
要么
getSnapshotBeforeUpdate(prevProps, prevState){
...
}