1

React hook 使用疑惑

 1 week ago
source link: https://www.v2ex.com/t/1035266
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  React

React hook 使用疑惑

  devzhaoyou · gezhaoyou · 1 小时 27 分钟前 · 482 次点击
const [count, setCount] = useState(0);

const fetch = () => {
  fetchMoreData(count)
};

const handleClick = () => {
  // 每次 fecth 前都要重置一下 count
  setCount(0);
  fetch()
};

这段代码 每次 handleClick 都要重置 count 的值为 0 ,然后使用 fetch 获取数据,fetch 会使用 count 的值; 如果上面的写法的问题是,count 在使用的时候并没有设置为 0

如果改为 useEffect 方式,如果 count 的值没有变化,又不会触发

const [count, setCount] = useState(0);

const fetch = () => {
  fetchMoreData(count)
};

useEffect(() => {
  fetch();
}, [count]);

const handleClick = () => {
  // count 的值之前就是 0 ,上面的 useEffect 不触发
  setCount(0);
};

所以,上面的这种情况该如何处理呢? 刚接触 react 感觉很简单的逻辑,在 react 里处理起来好复杂


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK