小编Uji*_*T34的帖子

在恒定条件下调用react挂钩是否安全?

钩的规则要求,同样的挂钩,并在同一顺序呼吁每一个渲染。并且有一个关于如果您违反此规则会出问题的解释。例如此代码:

function App() {
  console.log('render');
  const [flag, setFlag] = useState(true);
  const [first] = useState('first');
  console.log('first is', first);
  if (flag) {
    const [second] = useState('second');
    console.log('second is', second);
  }
  const [third] = useState('third');
  console.log('third is', third);

  useEffect(() => setFlag(false), []);

  return null;
}
Run Code Online (Sandbox Code Playgroud)

输出到控制台

render 
first is first 
second is second 
third is third 
render 
first is first 
third is second 
Run Code Online (Sandbox Code Playgroud)

并导致警告或错误。

但是,在元素生命周期中不会改变的条件又如何呢?

const DEBUG = true;

function TestConst() {
  if (DEBUG) {
    useEffect(() => console.log('rendered'));
  }

  return <span>test</span>; …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs eslint react-hooks

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

标签 统计

eslint ×1

javascript ×1

react-hooks ×1

reactjs ×1