首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单击Rerender组件

单击Rerender组件
EN

Stack Overflow用户
提问于 2022-09-11 21:04:46
回答 2查看 59关注 0票数 1

当单击按钮时,我正在尝试生成一个新的引用。很难搞清楚如何实现这一点。谷歌搜索让我相信,useCallback挂钩是可行的,但我没有任何经验,所以我还没有任何运气来实现它。任何帮助都是非常感谢的!提前谢谢你。

代码语言:javascript
复制
/* eslint-disable react-hooks/rules-of-hooks */
import React, { useEffect, useState, useCallback } from 'react'

const Main = () => {

 const [quote, setQuote] = useState(null)
 const [author, setAuthor] = useState(null)
 const [newQuote, setNewQuote] = useState(false)
 useEffect(() => {
    fetch('https://type.fit/api/quotes')
     .then(response => response.json())
     .then((data) => {
        let randomIndex = Math.floor((Math.random() * data.length));
    
        setQuote(data[randomIndex].text)
        setAuthor(data[randomIndex].author)
        
      })
     .catch(err => console.error(err));
    
  }, [])

  return (
    <div id='main' className='grid place-items-center h-screen w-screen text-center'>
     {/* Quote Gen Container */}
     <div className='flex flex-col justify-start mx-auto bg-sky-300 w-3/4 h-3/4 text-black space-y-3 p-32 rounded-3xl relative'>
      <h1 className='text-bold text-3xl absolute top-0 mx-auto'>Random Quote Generator</h1>
      <div>
        <h4 id="text">{`"${quote}"`}</h4>
      </div>
      <div>
        <p id="author">{`- ${author}`}</p>
      </div>
      <div id="button">
        <button onClick={() => setNewQuote(null)} className='bg-black text-white rounded-xl p-2 abs'>New Quote</button>
      </div>
     </div>
    </div>
  )
}

export default Main
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-11 21:10:51

将获取逻辑重构为回调,该回调可以从useEffect钩子调用,也可以直接在按钮的onClick处理程序中调用。

代码语言:javascript
复制
const Main = () => {
  const [quote, setQuote] = useState({});

  // Memoize a stable callback function reference
  const fetchQuote = useCallback(() => {
    fetch('https://type.fit/api/quotes')
      .then(response => response.json())
      .then((data) => {
        const randomIndex = Math.floor((Math.random() * data.length));
    
        setQuote(quotes[randomIndex]);
      })
      .catch(err => console.error(err));
  }, []);

  // Initial fetch of quotes
  useEffect(() => {
    fetchQuote();
  }, [fetchQuote]);

  if (!quote) return null;

  return (
    <div id='main' className='....'>
     {/* Quote Gen Container */}
     <div className='....'>
      <h1 className='....'>Random Quote Generator</h1>
      <div>
        <h4 id="text">{`"${quote.text}"`}</h4>
      </div>
      <div>
        <p id="author">{`- ${quote.author}`}</p>
      </div>
      <div id="button">
        <button
          onClick={fetchQuote} // <-- attach callback to fetch quote
          className='....'>
          New Quote
        </button>
      </div>
     </div>
    </div>
  )
}

如果获取的数据没有改变,那么获取一次,然后选择一个随机引号。

代码语言:javascript
复制
const Main = () => {
  const [quotes, setQuotes] = useState([]);
  const [quote, setQuote] = useState(null);

  // Memoize function to set single random quote
  const getQuote = useCallback(() => {
    const randomIndex = Math.floor((Math.random() * quotes.length));
    setQuote(quotes[randomIndex]);
  }, [quotes]);

  // Mounting useEffect to fetch and save all quotes
  // and set initial random quote
  useEffect(() => {
    fetch('https://type.fit/api/quotes')
      .then(response => response.json())
      .then((data) => {
        setQuotes(data);

        const randomIndex = Math.floor((Math.random() * data.length));
        setQuote(data[randomIndex]);
      })
      .catch(err => console.error(err));
  }, []);

  if (!quote) return null;

  return (
    <div id='main' className='....'>
     {/* Quote Gen Container */}
     <div className='....'>
      <h1 className='....'>Random Quote Generator</h1>
      <div>
        <h4 id="text">{`"${quote.text}"`}</h4>
      </div>
      <div>
        <p id="author">{`- ${quote.author}`}</p>
      </div>
      <div id="button">
        <button
          onClick={getQuote}
          className='....'
        >
          New Quote
        </button>
      </div>
     </div>
    </div>
  )
}
票数 2
EN

Stack Overflow用户

发布于 2022-09-11 21:10:47

假设您不需要每次在状态中存储返回的数据时重新获取数据,那么onclick只需选择一个新的随机条目来设置为“当前”引用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73682639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档