是的,它是在反應的反模式。組件卸載後可能會執行this.setState({ results: res.results })
。
最好的方法是將狀態(搜索掛起/搜索解析)移出反應組件。您可以利用redux
+ redux-thunk
或mobx
或flux
來幫助您。對於簡單的情況,你可以建立一個可取消的承諾。
const makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
val => hasCanceled_ ? reject({isCanceled: true}) : resolve(val),
error => hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
class MyComponent extends Component {
componentDidMount() {
this.cancellableSearch = makeCancelable(this.props.doSearch());
this.cancellableSearch.then((res) => {
this.setState({ results: res.results });
}).catch((reason) => {
if (!isCanceled.isCanceled) {
console.error('some error occurs', reason);
}
})
}
componentWillUnmount() {
this.cancellableSearch.cancel();
}
// ...
}
撤銷的承諾的代碼是從這裏複製:https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html
是的, ,我知道反應是爲了視圖,這就是爲什麼我問這個問題。我的問題出現了,因爲我覺得,一旦用戶選擇了ID,我就可以將其存儲在商店中,我必須再次清空商店的這一部分,因爲這是暫時的,也許還有其他方法可以做到這一點。 – Kossel