首页 > 其他 > 详细

[React] Use the React Effect Hook in Function Components

时间:2019-10-31 21:18:02      阅读:163      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/Answer1215/p/11773726.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!