• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

UseEffect

武飞扬头像
Yuiki
帮助1

Can we do sth after a render or re-render? We can! These are called side-effects or effects. This is what effects are for - doing after(& unrelated to) a render. This is useful for different kinds of things:

  • Changing parts of the DOM not covered by React
  • Async operations, like AJAX requests (requiring an API) when a component is mounted
  • Doing things when a component is about to be unmounted.

Effects are used for "side-effects": doing things unrelated to render// I am kind of confused about this.

Fetching Data

export default function QuateFetcher(){
  async function fetchQuote(){
  const response = await fetch(Randon_url)}//url 自己要定义一下
  const jsonResponse = await response.json(); //接下来自己选择要的内容
}

当我们需要页面第一次render就fetch info 而且仅需要fetch一次的时候,用useEffect。

Getting Data via AJAX on mount

When a component renders, fetch data from an API.

  • Data fetching is asynchronous, and may take a moment to complete
  • want to show user something, like a loading message, while fetching

To fetch correctly:

  • Having an effect that runs only once
  • Inside effect, when API calls is finished, will set state & re-render
/*example show how to fetch a random json*/
RANDOM_JSON_URL = ... /*insert json url*/
useEffect(()=>{
  async function getInitialQuote(){
    const response = await fetch(RANDOM_JSON_URL);
    const JsonResponse = await response.json();
    const randomQuote = jsonResponse.quote;
    setQuote(randomQuote);
  }
  getInitialQuote();/*because it is a async function, so it needs to be done this way.*/
},[]);

加入loader

const [isLoading, setLoading] = useState(true);

useEffect(()=>{ ...
setIsLoading(false);
})

必要地方加入 {isLoading && <p>Loading...</p>} 这个写法太漂亮了。 或者 <p className="Loader" style={{opacity: isLoading? 1:0}}></p> css: .Loader{transition: 1s opacity} //可以改为spinner loader

额外阅读

juejin.cn/post/716693…

这一篇写的贼好贼干净的讲解了useEffect的作用和何时正确return的做法。 可以先看www.youtube.com/watch?v=0ZJ… 后了解useEffect后再学习文章,更有利于理解。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgajfkh
系列文章
更多 icon
同类精品
更多 icon
继续加载