简体   繁体   English

React Hooks只能在函数组件的主体内部调用

[英]React Hooks can only be called inside the body of a function component

How do I trigger useEffect() on a button click, rather than on rendering the component? 如何在按钮单击时触发useEffect() ,而不是在渲染组件时触发?

When I use it inside a function like this, I get an error stating: 当我在这样的函数中使用它时,我得到一个错误说明:

Hooks can only be called inside the body of a function component 钩子只能在函数组件的主体内部调用

function App() {

  function buttonClicked() {  
    useEffect(() => {
      // Fetch from API
    });
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <h1 className="App-title">App Title</h1>
      </header>
      <p className="App-intro">
        To get started, edit <code>src/App.js</code> and save to reload.
      </p>
      <button onClick={buttonClicked}>Make API Call</button>
    </div>
  );
}

The accepted answer isn't exactly correct IMO. 接受的答案并不完全正确IMO。 If your goal is to trigger data fetching upon clicking on a button, there's no need for useEffect . 如果您的目标是在单击按钮时触发数据提取,则无需使用useEffect useEffect is used to replace the lifecycle hooks - componentDidMount , componentDidUpdate , and componentWillUnmount . useEffect用于替换生命周期钩子 - componentDidMountcomponentDidUpdatecomponentWillUnmount

Think about this - without hooks, will you need these lifecycle hooks at all to achieve what you want? 想想这个 - 没有钩子,你需要这些生命周期钩子来实现你想要的吗? With classes, you simply have to use this.state and a callback that triggers upon clicking of the button; 使用类,您只需使用this.state和单击按钮时触发的回调; you wouldn't use any of these lifecycle hooks. 你不会使用任何这些生命周期钩子。

The side effect you want to achieve is data fetching, but that's a user-triggered effect and useEffect is not helpful here. 您想要实现的副作用是数据提取,但这是用户触发的效果,而useEffect在这里没有用。 useEffect is only helpful when you want to have side effects during the lifecycle of the component. useEffect仅在您希望在组件的生命周期中产生副作用时才有用。

The code below should do what you want to achieve with hooks, and you don't need useEffect , you only need useState . 下面的代码应该用钩子做你想要的,而你不需要useEffect ,你只需要useState

 function App() { const [user, setUser] = React.useState(null); function fetchData() { fetch('https://randomuser.me/api/') .then(results => results.json()) .then(data => { setUser(data.results[0]); }); }; return <div> <p>{user ? user.name.first : 'No data'}</p> <button onClick={fetchData}>Fetch Data</button> </div>; } ReactDOM.render(<App/>, document.getElementById('app')); 
 <script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script> <div id="app"></div> 

Sounds like you misunderstood the usage of useEffect . 听起来你误解了useEffect的用法。 It's like componentDidUpdate hook - it is being triggered depending on value change, not directly by some function. 它就像componentDidUpdate钩子一样 - 它根据值的变化而被触发,而不是直接由某个函数触发。 When render method is called, useEffect is also called. 调用render方法时,也会调用useEffect Hard to tell what is your goal, but from your snippet it makes most sense just to call fetch without any hook. 很难说你的目标是什么,但是从你的片段来看,最有意义的就是在没有任何钩子的情况下调用fetch But to answer your question, one way to trigger useEffect would be to update your state and you can create useEffect hook to be triggered only if value of particular property is changed: 但是要回答你的问题,触发useEffect一种方法是更新你的状态,你可以创建useEffect钩子,只有在特定属性的值被改变时才被触发:

const [buttonClicked, setButtonClicked] = useState(false);

useEffect(() => {
  // Fetch from API
}, [buttonClicked]); 

<button onClick={() => setButtonClicked(true)}>Make API Call</button>

Now when you click, useEffect should be triggered, but because you added , [buttonClicked] , it won't be called if any other property value changes. 现在当你点击时,应该触发useEffect ,但是因为你添加了, [buttonClicked] ,如果任何其他属性值改变,它将不会被调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 react native hooks 只能在函数组件的主体内部调用 - react native hooks can only be called inside body of a function component React Hooks 错误:只能在函数组件内部调用 Hooks - React Hooks Error: Hooks can only be called inside the body of a function component 在 HOC 中使用 useState/Hooks 导致错误“Hooks can only be called inside of a function component” - React Using useState/Hooks In HOC Causes Error "Hooks can only be called inside of the body of a function component" 无法解决,只能在function组件的body内部调用Hooks - Unable to Solve , Hooks can only be called inside of the body of a function component 钩子只能在函数组件错误的主体内部调用 - Hooks can only be called inside the body of a function component error Invariant Violation:Hooks 只能在函数组件内部调用 - Invariant Violation: Hooks can only be called inside the body of a function component 反应:无效的挂钩调用。 挂钩只能在功能组件的主体内部调用 - React: Invalid hook call. Hooks can only be called inside of the body of a function component 反应钩子错误:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React hook Error: Invalid hook call. Hooks can only be called inside of the body of a function component 反应路由器:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React Router: Invalid hook call. Hooks can only be called inside of the body of a function component react-router-dom: 无效的钩子调用,只能在 function 组件的主体内部调用钩子 - react-router-dom: Invalid hook call, Hooks can only be called inside of the body of a function component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM