te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - React Hooks can only be called inside the body of a function component - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Hooks can only be called inside the body of a function component - Stack Overflow

programmeradmin4浏览0评论

How do I trigger useEffect() on a button click, rather than on rendering the ponent?

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 ponent

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>
  );
}

How do I trigger useEffect() on a button click, rather than on rendering the ponent?

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 ponent

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>
  );
}
Share Improve this question edited Nov 11, 2018 at 21:30 Yangshun Tay 53.2k33 gold badges123 silver badges150 bronze badges asked Nov 11, 2018 at 13:37 AlanAlan 4,3253 gold badges23 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

If your goal is to trigger data fetching upon clicking on a button, there's no need for useEffect. useEffect is used to replace the lifecycle hooks - ponentDidMount, ponentDidUpdate, and ponentWillUnmount.

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; 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 is only helpful when you want to have side effects during the lifecycle of the ponent.

The code below should do what you want to achieve with hooks, and you don't need useEffect, you only need 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./[email protected]/umd/react.development.js"></script>
<script src="https://unpkg./[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

Sounds like you misunderstood the usage of useEffect. It's like ponentDidUpdate hook - it is being triggered depending on value change, not directly by some function. When render method is called, useEffect is also called. Hard to tell what is your goal, but from your snippet it makes most sense just to call fetch without any hook. 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:

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.

发布评论

评论列表(0)

  1. 暂无评论