简体   繁体   中英

how to disabled a button while loading, but won't affect the pagination function (React.js)

Question about disabled in React.js

I try to disabled a button while loading and then after complete render(or said get the data) it will abled the button.

Here is the example in Codesandbox link: https://codesandbox.io/s/data-fetch-example-oc8eh0?file=/src/App.js

scenario like: every time I click "first", "previous", "next" and "last" button. all the buttons will be disabled (not just the button which being clicked) when a page of data is currently being loaded.

Thank you

Here is the code if you can't open the link:

import React,{ useState, useEffect } from "react";
import "./styles.css";

export default function App() {

  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(0);
  const [postsPerPage, setPostsPerPage] = useState(10);

  useEffect(()=>{
    getData();
  },[])

  async function getData(){
    setLoading(true);    
    const response = await fetch('https://stream-restaurant-menu-svc.herokuapp.com/item?category')
    let actualData = await response.json();
    setPosts(actualData)
    setLoading(false);   
  }

  const indexOfLastPost = (currentPage + 1) * postsPerPage;
  const indexOfFirstPost = indexOfLastPost - postsPerPage;
  const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
 
    const pageNumbers = [];

    for (let i = 0; i < Math.ceil(posts.length / postsPerPage); i++) {
      pageNumbers.push(i);
    }
  
    const incrementPageNumber = () => {
      if (currentPage < pageNumbers.length - 1) {
        setCurrentPage((previousPageNumber) => previousPageNumber + 1);
      }
    };
  
    const decrementPageNumber = () => {
      if (currentPage > 0) {
        setCurrentPage((previousPageNumber) => previousPageNumber - 1);
      }
    };
    // if loading...
  if(loading){
    return <h2>Loading</h2>
  }

  return (
    <div className="App">
      <table className="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
          </tr>
        </thead>
        <tbody>
          {currentPosts.map((post) => (
            <tr>
              <td key={`${post.id}-id`}>{post.id}</td>
              <td key={`${post.name}-firstName`}>{post.name}</td>
              <td key={`${post.short_name}-lastName`}>{post.short_name}</td>
            </tr>
          ))}
        </tbody>
      </table>
      <div>
      <button 
      id='first'
      type='button'
      className='first-page-btn'
      disabled={loading || currentPage === 0}
      onClick={() => {setCurrentPage(0)}}
      >
        first
      </button>

      <button 
      id='previous'
      type='button'
      className='previous-page-btn'
      disabled={loading || currentPage === 0}
      onClick={decrementPageNumber}
      >
        previous
        </button>

      <button 
      id='next'
      type='button'
      className='next-page-btn'
      disabled={loading || currentPage === pageNumbers[pageNumbers.length - 1]}
      onClick={incrementPageNumber}
      >
      next
      </button>

      <button 
      id='last'
      type='button'
      className='last-page-btn'
      disabled={loading || currentPage === 0}
      onClick={() => setCurrentPage(pageNumbers[pageNumbers.length - 1])}
      >
      last
      </button>
      </div>
    </div>
  );
}

enter image description here

您似乎只在初始安装时更改getData中的加载状态(而不是在单击按钮时。并且在加载时您返回<h2>Loading</h2>而不是整个表,因此如果禁用表内的按钮并不重要或不在加载时。

Unfortunately, I cannot open your link. Here is my thought. I guess you might have loading state in main component. If not, you might have data state which is the data you want to download and update in each pagination.
I will use loading as example. Your component might be similar to this.

function Main() {
    return(
        <div>
            <Pagination disabled={loading} {...other props} />
        </div>
     )

Then, add disabled props to Pagination. I think your pagination are button component, then it has disabled attribute. Or, if you use bootstrap, you can pass disabled className to button or a element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM