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

Tips #54

Open
imfenghuang opened this issue Jul 7, 2024 · 0 comments
Open

Tips #54

imfenghuang opened this issue Jul 7, 2024 · 0 comments

Comments

@imfenghuang
Copy link
Owner

Tips 1

React 源码里有很多地方用到了 try {} finally {},它的执行逻辑如以下代码所示。简而言之,finally 包括的代码总会执行,无论前面 try 包裹的内容是否正常或抛错。React 里使用这种方式,用来保证 try 代码块内代码即使执行错误,也能保证状态被还原(如 commitRoot 中的示例)。

  • 方式 1
var foo = () => {
  console.log(2);
}
var bar = () => {
  try {
    console.log(1);
    return foo()
  } finally {
    console.log(3);
  }
}
bar();// 1 2 3
  • 方式 2
var foo = () => {
  console.log(2);
  throw new Error()
}
var bar = () => {
  try {
    console.log(1);
    return foo()
  } catch(err) {
    console.log(4)
  } finally {
    console.log(3);
  }
}
bar(); // 1 2 4 3
  • 方式 3
var foo = () => {
  console.log(2);
}
var bar = () => {
  try {
    console.log(1);
    throw new Error()
    return foo()
  } catch(err) {
    console.log(4)
  } finally {
    console.log(3);
  }
}
bar(); // 1 4 3
function commitRoot(
  root: FiberRoot,
  recoverableErrors: null | Array<CapturedValue<mixed>>,
  transitions: Array<Transition> | null,
) {
  // 获取全局变量 currentUpdatePriority 的值
  // 即当前更新优先级
  const previousUpdateLanePriority = getCurrentUpdatePriority();
  const prevTransition = ReactCurrentBatchConfig.transition;

  try {
    // 重置当前 ReactCurrentBatchConfig 为 null
    ReactCurrentBatchConfig.transition = null;
    // 设置当前更新优先级 currentUpdatePriority 为 DiscreteEventPriority
    setCurrentUpdatePriority(DiscreteEventPriority);
    // 调用 commitRootImpl
    commitRootImpl(
      root,
      recoverableErrors,
      transitions,
      previousUpdateLanePriority,
    );
  } finally {
    // 执行完,还原 ReactCurrentBatchConfig 和 currentUpdatePriority
    ReactCurrentBatchConfig.transition = prevTransition;
    setCurrentUpdatePriority(previousUpdateLanePriority);
  }

  return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant