标签:target and log hang ons turn api on() function
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
标签:target and log hang ons turn api on() function
原文地址:https://www.cnblogs.com/Answer1215/p/11773726.html