当使用 HMR 时,react 似乎清除状态并将其放回原处,但我创建了一个钩子,该钩子返回一个函数,该函数返回从对话框中解析的承诺。
我尝试使用 useEffect 清除状态并删除我的所有对话框,但 react 清除了状态,然后卸载挂钩,然后放回状态,我可以卸载列表的唯一方法是使用 ref 但我获得不一致的状态。
我不能保持“原样”,因为我在我的网站上打开了一个对话框,由于我的回调被删除,我无法关闭该对话框。
我的提供者(在应用顶部调用并提供上下文)
@Getter
@Setter
public class ColumnconfigDto {
@JsonProperty("key")
private String key;
@JsonProperty("label")
private String label;
@JsonProperty("isVisible")
private Boolean isVisible;
@JsonProperty("position")
private Integer position;
@JsonProperty("isSortable")
private Boolean isSortable;
@JsonProperty("isHideable")
private Boolean isHideable;
}
我在组件中使用的钩子:
export function useProvideConfirmation(): ProviderConfirmationAPI {
const [contents,setContents] = useState<ConfirmationAPI["contents"]>([]);
return {
contents,confirm(
content: ReactElement | ReactNode,options: ConfirmOptions = { closable: true },): Promise<void> {
return new Promise((resolve,reject) => {
setContents((prevContents) => [
...prevContents,[content,options,[resolve,reject]],]);
});
},removeContent(content) {
setContents((prevContents) =>
deleteFromArrayAndReturn(
prevContents,prevContents.findIndex((c) => c[0] === content),),);
},};
}
一个示例组件:
export function useConfirmation(): ConfirmationAPI {
const [currentContents,setCurrentContents] = useState<Props["content"][]>(
[],);
const context = useContext(ConfirmationContext);
const contentsref = useRef<Props["content"][]>();
contentsref.current = currentContents;
useEffect(() => {
return () => {
contentsref.current?.forEach((c) => {
context.removeContent(c);
});
};
},[]);
return useMemo(
() => ({
...context,confirm(content,...otherParams) {
setCurrentContents((prevContents) => [...prevContents,content]);
return context.confirm(content,...otherParams).then((value) => {
context.removeContent(content);
return value;
});
},}),[context],);
}
有关完整的工作示例,请检查 the codesandbox