小编Rin*_*ala的帖子

为什么在顶层调用 React Hook?

我正在阅读 React-hooks 概念。我经历了一条规则,上面写着Don't call React hooks inside conditions。他们在这里提供了解释链接

function Form() {
  // 1. Use the name state variable
  const [name, setName] = useState('Mary');

  // 2. Use an effect for persisting the form
  useEffect(function persistForm() {
    localStorage.setItem('formData', name);
  });

  // 3. Use the surname state variable
  const [surname, setSurname] = useState('Poppins');

  // 4. Use an effect for updating the title
  useEffect(function updateTitle() {
    document.title = name + ' ' + surname;
  });

  // ...
}
Run Code Online (Sandbox Code Playgroud)

我明白他们想说什么,但我无法得到确切的原因,比如为什么我不能在 if-else …

reactjs react-hooks

7
推荐指数
2
解决办法
1万
查看次数

标签 统计

react-hooks ×1

reactjs ×1