簡體   English   中英

單擊 ReactJS 時按鈕僅工作一次

[英]Button working only one time on clicking in ReactJS

我在 React 中創建了一個帶有功能組件的隨機報價機項目。 當我點擊新報價時,它只工作一次。 這是 freecodecamp 挑戰項目之一。 在這里,每次單擊新報價按鈕時,我都會嘗試獲取新報價。 我無法發現問題。 請幫忙。

import React, {useState} from "react";
import {Button, Card, Col, Container, Row} from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTwitter } from "@fortawesome/free-brands-svg-icons";

const quotes = [
  {
    quote: "The greatest glory in living lies not in never falling, but in rising every time we fall.",
    author: "Nelson Mandela"
  },
  {
    quote: "The way to get started is to quit talking and begin doing.",
    author: "Walt Disney"
  },
  {
    quote: "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking." ,
    author: "Steve Jobs"
  },
  {
    quote: "If life were predictable it would cease to be life, and be without flavor.",
    author: "Eleanor Roosevelt"
  },
  {
    quote: "If you look at what you have in life, you'll always have more. If you look at what you don't have in life, you'll never have enough.",
    author: "Oprah Winfrey"
  },
  {
    quote: "If you set your goals ridiculously high and it's a failure, you will fail above everyone else's success.",
    author: "James Cameron"
  },
  {
    quote: "Life is what happens when you're busy making other plans.",
    author: "John Lennon"
  },
  {
    quote: "Spread love everywhere you go. Let no one ever come to you without leaving happier.",
    author: "Mother Teresa"
  },
  {
    quote: "When you reach the end of your rope, tie a knot in it and hang on.",
    author: "Franklin D. Roosevelt"
  },
  {
    quote: "It is during our darkest moments that we must focus to see the light.",
    author: "Aristotle"
  },
];
const colors = [
  "#ffdecf",
  "#d3dbff",
  "#8fcfd1",
  "#eeecda",
  "#383e56",
  "#89c9b8",
  "#cff6cf",
  "#726a95",
  "#abc2e8",
  "#303960"
];

const rand_num = Math.floor(Math.random()*quotes.length);

export const Quoter = () => {

  const [quote, setQuote] = useState(quotes[0].quote);
  const [author, setAuthor] = useState(quotes[0].author);
  const [color, setColor] = useState(colors[0]);


  const handleQuote = () => {
    return (
      setQuote(quotes[rand_num].quote),
      setAuthor(quotes[rand_num].author),
      setColor(colors[rand_num])
    )
  }


  return (
    <Container id="quote-box">
      <Row className="d-flex justify-content-center align-items-center">
        <Card>
          <Card.Body style={{width: "18rem"}}>
            <Card.Text id="text" style={{color: color}}>
              {quote}
              <Col>
                <p id='author'>-{author}</p>
              </Col>
            </Card.Text>
                <Button id='tweet-quote'><Card.Link href=""><FontAwesomeIcon icon={faTwitter}/></Card.Link></Button>
                <Button id='new-quote'
                        onClick={handleQuote}
                >
                  New Quote
                </Button>
          </Card.Body>
        </Card>
      </Row>
    </Container>
  )
}

每次您的組件中都有相同的 rand_num 值。

每次都需要生成一個新值,用let替換const。

const handleQuote = () => {
     rand_num = Math.floor(Math.random()*quotes.length);

    return (
      setQuote(quotes[rand_num].quote),
      setAuthor(quotes[rand_num].author),
      setColor(colors[rand_num])
    )
  }

當您在主要組件Quoter之外定義常量 rand_num 時,該邏輯僅在您的代碼第一次運行時執行一次。 這一點,rand_num 總是攜帶相同的值。

將變量聲明移動到 Quoter 的scope中將解決該問題。 最好的方法是將常量聲明放在 handleQuote 方法中。 此外,作為一個建議並為了保持清晰的一致性,您不應在 handleQuote 上使用 return,因為您並沒有真正使用該方法返回任何值。 該代碼仍然可以正常使用 return,但它在技術上是不正確的。

  const handleQuote = () => {
    const rand_num = Math.floor(Math.random()*quotes.length);

    setQuote(quotes[rand_num].quote);
    setAuthor(quotes[rand_num].author);
    setColor(colors[rand_num]);
  }

請注意,每次調用它都會生成一個隨機值,並為每個 useState 操作使用相同的 rand_num 值。 如果您希望每個人都有自己的隨機數,您應該在每個人上單獨使用 Math.floor 邏輯(也許將其提取到另一種方法中)。

  const getRandomNum= () => Math.floor(Math.random()*quotes.length);
  
  const handleQuote = () => {
    setQuote(quotes[getRandomNum()].quote);
    setAuthor(quotes[getRandomNum()].author);
    setColor(colors[getRandomNum()]);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM