从嵌套函数调用钩子

Call hook from nested functions

我使用钩子创建了一个功能组件 MyComponent。我想知道将 setState 传递给另一个函数 renderList 是否可以?我试过它工作正常,但根据 hooks 文档:Only call Hooks at the top level。不要在循环、条件或嵌套函数中调用 Hooks。 这种情况算作从嵌套函数调用 hook 吗?

const MyComponent = (listProps) {
  const [state, setState] = useState(false);
  return (
    <div>
      renderList(listProps, setState);
    </div>
  );
}

renderList(listProps, setState){
  return (
    <ul>
     {
       listProps.map(item => {
         // call setState() with a value here;
         return <li>{item}</li>;
       });
     }
    </ul>
  );
}

上述将 setter 传递给函数的方式非常好,不算作

的场景

Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions

因为你实际上是在调用函数组件顶部的钩子useStateuseState 返回的 setter 可以在任何地方调用,通过将其作为 prop 传递给子组件或传递给返回 JSX 元素的函数

您唯一需要注意的是您不是直接在渲染中调用 setter,而是在事件或效果中调用。

P.S. There are some syntactical errors that you need to rectify in your code though

工作演示

const MyComponent = ({listProps}) => {
  const [state, setState] = React.useState('');
  return (
    <div>
      {renderList(listProps, setState)}
    </div>
  );
}

const renderList = (listProps, setState) =>{
  return (
    <ul>
     {
       listProps.map(item => {
         // call setState() with a value here;
         return <li onClick={() => setState(item)}>{item}</li>;
       })
     }
    </ul>
  );
}

ReactDOM.render(<MyComponent listProps={['First', 'Second', 'Third']} />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root" />