码迷,mamicode.com
首页 > 其他好文 > 详细

[React] Use the React Effect Hook in Function Components

时间:2019-10-31 21:33:09      阅读:120      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!