首页 > 其他 > 详细

[React] Write a Custom React Effect Hook

时间:2019-11-01 23:09:51      阅读:115      评论:0      收藏:0      [点我收藏+]

Similar to writing a custom State Hook, we’ll write our own Effect Hook called useStarWarsQuote, which returns a random quote and a loading state.

Remember, hooks can only be used inside function components.

 

function useStarWarsQuote() {
  // defualt the quote to a empty value
  const [quote, setQuote] = useState(‘‘)
  // default the loading to false
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    async function getStarWarsQuote() {
      setLoading(true)
      // 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
      setQuote(quote)
      setLoading(false)
    }
    getStarWarsQuote()
  }, [])

  return { quote, loading }
}
export function FeedbackCustomComponent() {
  const [text, setText] = useText(‘‘)
  const { quote, loading } = useStarWarsQuote()

  useEffect(() => {
    if (quote) {
      setText(quote)
    }
  }, [quote, setText])
  // 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)
  }

  if (loading) return <p>Loading...</p>

  if (quote) {
    return (
      <Form onSubmit={e => handleSubmit(e)}>
        <Title>Custom 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>
    )
  }

  return null
}

 

[React] Write a Custom React Effect Hook

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

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