青训营react学习文档
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
额外阅读
这一篇写的贼好贼干净的讲解了useEffect的作用和何时正确return的做法。 可以先看www.youtube.com/watch?v=0ZJ… 后了解useEffect后再学习文章,更有利于理解。