Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 优化 useModel Executor组件 #11404

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 5 additions & 18 deletions packages/plugins/libs/model.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,38 +35,28 @@ class Dispatcher {

interface ExecutorProps {
hook: () => any;
onUpdate: (val: any) => void;
namespace: string;
}

function Executor(props: ExecutorProps) {
const { hook, onUpdate, namespace } = props;
const { hook, namespace } = props;

const updateRef = useRef(onUpdate);
const initialLoad = useRef(false);
const { dispatcher } = useContext<{ dispatcher: Dispatcher }>(Context);

let data: any;
try {
data = hook();
dispatcher.data[namespace] = data;
} catch (e) {
console.error(
`plugin-model: Invoking '${namespace || 'unknown'}' model failed:`,
e,
);
}

// 首次执行时立刻返回初始值
useMemo(() => {
updateRef.current(data);
}, []);

// React 16.13 后 update 函数用 useEffect 包裹
useEffect(() => {
if (initialLoad.current) {
updateRef.current(data);
} else {
initialLoad.current = true;
}
dispatcher.update(namespace);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这么改的意义是啥,上面渲染赋值是同步的,useEffect 里是异步的,不会值错乱吗

});

return null;
Expand All @@ -86,10 +76,7 @@ export function Provider(props: {
key={namespace}
hook={props.models[namespace]}
namespace={namespace}
onUpdate={(val) => {
dispatcher.data[namespace] = val;
dispatcher.update(namespace);
}}

/>
);
})}
Expand Down