【问题标题】:Pagination in React-ReduxReact-Redux 中的分页
【发布时间】:2021-06-14 07:37:19
【问题描述】:

所以我只是想做出一个pagination component 的反应。我目前使用redux 进行状态管理,并使用semantic-ui 进行分页组件。 我目前在我的action.jsx 文件中创建了一个反应组件,并且还有另外两个函数,其中一个用于data fetching 用于我的redux 状态,另一个用于声明当前active page 值并设置new target url 为数据获取。

    export class Paginator extends React.Component {


        state = {
            page: [],
            pages: []
          }
          
         handlePage(activePage) {
          let pagenum = activePage;
          let pagestring = pagenum.toString();
          paginationUrl = '/api/v1/products/index/?page=' + pagestring; ----> Pass This Url
        }


        componentDidMount() {
            axios.get("/api/v1/products/index", { withCredentials: true })
              .then(response => {
                  this.setState({
                    page: response.data.page,
                    pages: response.data.pages
                  })
              })
              .catch(error => {
                console.log("Check Login Error", error);
              });
        }

        render() {
            return(
                <Pagination onPageChange={this.handlePage} size='mini' siblingRange="6"
                defaultActivePage={this.state.page}
                totalPages={this.state.pages}
                />
            )
        }
    }


   export function fetchProducts() {
    return (dispatch) => {
        dispatch(fetchProductsRequest())
        axios
        .get("To Here !")
        .then(response => {
            // response.data is the products
            const products = response.data.products
            dispatch(fetchProductsSuccess(products))

        })
        .catch(error => {
            // error.message is the error message
            dispatch(fetchProductsFailure(error.message))
        })
    }
    }

问题是我如何将paginationUrl 传递给下面的函数? (实际上,我猜不可能!)。

注意:我只能在与分页组件相同的组件中使用handlePage

等待建议,谢谢提前;)

【问题讨论】:

    标签: reactjs redux react-redux pagination


    【解决方案1】:

    当在页面更改时调度操作时,您可以将 URL 传递给 fetchProducts 函数。

    handlePage(activePage) {
      const url = `/api/v1/products/index/?page=${activePage}`
      dispatch(fetchProducts(url))
    }
    

    并更新 fetchProducts 操作创建者以使用 URL。

    export function fetchProducts(url) {
      return (dispatch) => {
        dispatch(fetchProductsRequest())
        axios
          .get(url)
          .then((response) => {
            dispatch(fetchProductsSuccess(response.data.products))
          })
          .catch((error) => {
            dispatch(fetchProductsFailure(error.message))
          })
      }
    }
    

    这与问题无关,但我强烈建议使用React Query 来简化数据获取和同步。

    【讨论】:

    • 我只想补充一点,应该在 componentDidMount 调用中重用 fetchProducts。我还建议将该函数提取到不同的文件中。
    猜你喜欢
    • 1970-01-01
    • 2019-02-05
    • 2021-03-31
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2017-11-17
    • 2023-03-11
    • 2018-04-29
    相关资源
    最近更新 更多