如何在不刷新整个页面的情况下重新加载组件?

时间:2020-07-24 12:53:17

标签: javascript reactjs axios react-hooks react-component

任何帮助将不胜感激,我已经在React中构建了一个简单的报价生成器项目,希望在不渲染整个页面的情况下加载新报价。当前,即时消息使用钩子并且引号状态驻留在一个组件中,是否可以使用单击处理程序从另一组件重新加载/刷新状态?

项目链接:https://codesandbox.io/s/quote-generator-czffn?file=/src/components/buttons/Buttons.js

使用refreshPage函数当前如何重新加载。 谢谢!

import React from 'react';

const Buttons = ({ quotes, getNewQuote }) => {
  const twitterUrl = `https://twitter.com/intent/tweet?text=${quotes.joke}`;
  //   console.log(twitterUrl);

  function refreshPage() {
    window.location.reload(false);
  }

  return (
    <div className='button-container'>
      <button
        onClick={() => window.open(twitterUrl, '_blank')}
        className='twitter-button'
        id='twitter'
        tittle='Tweet This!'
      >
        <i className='fab fa-twitter'></i>
      </button>
      <button id='new-quote' onClick={refreshPage}>
        New Quote
      </button>
    </div>
  );
};

export default Buttons;

4 个答案:

答案 0 :(得分:1)

如果报价单要显示新报价单而不刷新整个页面,请从钩子中删除axios请求并将其放在自己的函数中。

  const getQuotes = () => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  }

// ...

<Buttons onClick={getQuotes} quotes={quotes} />

然后调整按钮以在单击时使用此功能:

const Buttons = ({ quotes, getNewQuote, onClick }) => {

// ...

<button id="new-quote" onClick={onClick}>
  New Quote
</button>

您可能希望在检索内容时添加动画,并使用useState进行加载,但这应该是一个好的开始。

=======更新=======

这也是一个示例代码,以了解其工作方式。 点击运行代码段以查看其正常运行。

const { useState, useEffect } = React;

const Quote = props => {
  return <section>
    <blockquote>
      {JSON.stringify(props.quote)}
    </blockquote>
    <button onClick={props.onClick}>Get Quote</button>
  </section>
}

const App = () => {
  const [quotes, setQuotes] = useState(null);
  const [loading, setLoading] = useState(true);
  
  const getQuotes = () => {
    setLoading(true);
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        if (res.data && res.data.joke) {
          setQuotes(res.data.joke);
        }
        setLoading(false);
      })
      .catch(err => {
        console.log(err);
        setLoading(false);
      });
  }
  
  useEffect(() => {
    getQuotes();
  }, []);

  return loading ? <p>Loading...</p> : <Quote quote={quotes} onClick={getQuotes} />
}


ReactDOM.render(<App />, document.querySelector('#root'));
body {
  background: #efefef;
  font-family: Arial, sans-serif;
  padding: 20px;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

section {
   background: white;
   border-radius: 6px;
   display: block;
   padding: 10px;
}

blockquote {
  padding: 10px;
  margin: 0 0 10px 0; 
  border-bottom: 1px solid #efefef;
  font-size: 21px;
}

button {
border-radius: 4px;
background: blue;
color: white;
border: none;
height: 40px;
padding: 0 12px;
font-size: 14px;
}

p {
  display: block;
  max-width: 80px;
  background: white;
  border-radius: 6px;
  padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/axios@0.19.2/dist/axios.min.js"></script>

<div id="root"></div>

答案 1 :(得分:0)

Codingwithmanny击败了我。

将axios调用放入其自己的函数中,并将该函数传递给按钮组件。

Quote.js:

import React, { useState, useEffect } from "react";
import Buttons from "../buttons/Buttons";
import axios from "axios";

const Quote = () => {
  const [quotes, setQuotes] = useState("");

  const fetchQuotes = () => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  };
  useEffect(() => {
    console.log("new quote requested");
  }, [quotes]);

  return (
    <div className="quote-text">
      <i className="fas fa-quote-left" />
      <span id="quote"> {quotes.joke}</span>
      <Buttons quotes={quotes} getNewQuote={fetchQuotes} />
    </div>
  );
};

export default Quote;

Buttons.js

import React from "react";

const Buttons = ({ quotes, getNewQuote }) => {
  const twitterUrl = `https://twitter.com/intent/tweet?text=${quotes.joke}`;
  //   console.log(twitterUrl);

  return (
    <div className="button-container">
      <button
        onClick={() => window.open(twitterUrl, "_blank")}
        className="twitter-button"
        id="twitter"
        tittle="Tweet This!"
      >
        <i className="fab fa-twitter" />
      </button>
      <button id="new-quote" onClick={getNewQuote}>
        New Quote
      </button>
    </div>
  );
};

export default Buttons;

Codesandbox:https://codesandbox.io/s/quote-generator-heufm

答案 2 :(得分:0)

您应该在单击按钮时调用New Qoute API。

您点击组件

import React from "react";

const Buttons = ({ quotes, getNewQuote }) => {
  const twitterUrl = `https://twitter.com/intent/tweet?text=${quotes.joke}`;
  //   console.log(twitterUrl);

  return (
    <div className="button-container">
      <button
        onClick={() => window.open(twitterUrl, "_blank")}
        className="twitter-button"
        id="twitter"
        tittle="Tweet This!"
      >
        <i className="fab fa-twitter" />
      </button>
      <button id="new-quote" onClick={getNewQuote}>
        New Quote
      </button>
    </div>
  );
};

export default Buttons;

您的Qoute组件:

import React, { useState, useEffect } from "react";
import Buttons from "../buttons/Buttons";
import axios from "axios";

const Quote = () => {
  const [quotes, setQuotes] = useState("");
  useEffect(() => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  }, []);

  const getNewQuote = () => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  }

  return (
    <div className="quote-text">
      <i className="fas fa-quote-left" />
      <span id="quote"> {quotes.joke}</span>
      <Buttons quotes={quotes} getNewQuote={getNewQuote}/>
    </div>
  );
};

export default Quote;

答案 3 :(得分:0)

您可以执行以下操作。

Quote.js中创建getNewQuote函数,并在useEffect内部调用该函数。

然后,将getNewQuote函数传递给Button组件,并在New Quote按钮onClick上设置getNewQuote

这是升级后的沙箱-> link

Quote.js

const Quote = () => {
  const [quotes, setQuotes] = useState("");
  useEffect(() => {
    getNewQuote();
  }, []);

  const getNewQuote = () => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  };

  return (
    <div className="quote-text">
      <i className="fas fa-quote-left" />
      <span id="quote"> {quotes.joke}</span>
      <Buttons getNewQuote={getNewQuote} quotes={quotes} /> // here you pass the getNewQuote function to the Buttons component
    </div>
  );
};

Buttons.js

const Buttons = ({ quotes, getNewQuote }) => {
  const twitterUrl = `https://twitter.com/intent/tweet?text=${quotes.joke}`;
  //   console.log(twitterUrl);

  return (
    <div className="button-container">
      <button
        onClick={() => window.open(twitterUrl, "_blank")}
        className="twitter-button"
        id="twitter"
        tittle="Tweet This!"
      >
        <i className="fab fa-twitter" />
      </button>
      <button id="new-quote" onClick={getNewQuote}> // here onClick you call the getNewQuote function
        New Quote
      </button>
    </div>
  );
};