反应useState等待设置状态

时间:2019-06-11 01:53:29

标签: reactjs

我正在将React Component转换为函数,并且我不习惯React的useHooks。我已经将以下内容转换为

handleRequestSort = (event, property) => {
    const { orderBy, order } = this.state;
    const isAsc = orderBy === property && order === "asc";
    this.setState(
      {
        order: isAsc ? "desc" : "asc",
        orderBy: property
      },
      this.getRows
    );
};

收件人

function handleRequestSort(event, property) {
    const isAsc = orderBy === property && order === "asc";
    setOrder(isAsc ? "desc" : "asc");
    setOrderBy(property);
    getRows();
}

但是问题在于,现在已经在设置order和orderBy状态之前运行getRows(),弄乱了我的getRows功能

任何帮助都会为他们加油。

1 个答案:

答案 0 :(得分:1)

您可以使用带回调的使用状态库

https://www.npmjs.com/package/use-state-with-callback

import useStateWithCallback from 'use-state-with-callback';

const Index = () => {
    const [orderState, setOrderState] = useStateWithCallback({}, (state) => {
        const {orderBy, order} = state;
        if(order && orderBy){
            getRows()
        }
    })

    const {orderBy, order} = orderState;

    const handleRequestSort = (event, property) => {
        const isAsc = orderBy === property && order === "asc";
        setOrderState({
            order : isAsc ? "desc" : "asc",
            orderBy : property
        })
    }

    return(...)
}


import React, {useEffect, useState} from 'react';

const Index = () => {
    const [orderState, setOrderState] = useState({});

    const {orderBy, order} = orderState;

    const handleRequestSort = (event, property) => {
        const isAsc = orderBy === property && order === "asc";
        setOrderState({
            order : isAsc ? "desc" : "asc",
            orderBy : property
        })
    }

    useEffect(() => {
        if(orderBy && order){
            getRows()
        }
    },[orderState])

    return (...)
}