[React] Use the React Effect Hook in Function Components
Posted answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Use the React Effect Hook in Function Components相关的知识,希望对你有一定的参考价值。
Similar to the State Hook, the Effect Hook is “first-class” in React and handy for performing side effects in function components. The Effect Hook is called by passing a function as the first argument. Here, you can perform side effects. If needed, you can pass an optional second argument, which is an array of dependencies. This tells React, "Only run my effect when these values change."
A tip from Ryan Florence on using the dependency array:
"with which state does this effect synchronize with."
import React, { useState, useEffect } from ‘react‘ import { Form, Label, Textarea, Button, Title } from ‘./Feedback.styles‘ export function FeedbackEffectComponent() { const [text, setText] = useState(‘‘) useEffect(() => { async function getStarWarsQuote() { // Get initial text const response = await fetch( ‘https://starwars-quote-proxy-gi0d3x1lz.now.sh/api/randomQuote‘ ) const data = await response.json() const quote = data.starWarsQuote setText(quote) } getStarWarsQuote() }, []) // Handle form submission function handleSubmit(e) { e.preventDefault() console.log(`Submitting response to API: "${text}"`) setText(‘‘) } // Update text in state onchange for textarea function handleTextChange(e) { const updatedText = e.target.value setText(updatedText) } return ( <Form onSubmit={e => handleSubmit(e)}> <Title>Effect Example</Title> <Label> Have feedback for our team? <br /> Let us know here ?? <Textarea value={text} onChange={e => handleTextChange(e)} /> </Label> <Button type="submit">Submit</Button> </Form> ) }
以上是关于[React] Use the React Effect Hook in Function Components的主要内容,如果未能解决你的问题,请参考以下文章
[React] Use the React Effect Hook in Function Components
[React] Use React.ReactNode for the children prop in React TypeScript components and Render Props(代码
[React Router v4] Use the React Router v4 Link Component for Navigation Between Routes
React Cannot use JSX unless the ‘--jsx‘ flag is provided.
React Cannot use JSX unless the ‘--jsx‘ flag is provided.
Taro+react开发(32) Please use the ‘new‘ operator, this DOM object constructor cannot be called as a fu