如何在React钩子中的状态更改后立即获得状态

时间:2020-10-27 08:20:00

标签: reactjs typescript

嗨,大家好,我无法设置当前状态。我在传递该状态的地方调用一个函数,但是我总是在该函数中获得默认状态。 这是我的状态-

const [currentValue , setCurrentValue] = useState(one[0]); // where one[0] is string "Test"

这是我的onchange函数-

const getTest = useCallback((newValue:string) => {
 setCurrentValue({
    label:newValue,
    value:newValue
});
  getCurrentValue(currentValue.value);
  getSortOrder()
}, [])

这是我的getSortOrder函数-

const getSortOrder  =() => {
console.log(currentValue);
}

我在getSortOrder函数和getCurrentValue函数中没有得到更新状态。但是是的,如果我试图在渲染中控制状态,那么它将向我显示更新的状态,但在功能上却没有更新。如何在两个功能中都达到更新状态?

2 个答案:

答案 0 :(得分:1)

如果我正确回答了您的问题,那么这可能会有所帮助:

const getTest = useCallback((newValue:string) => {
 setCurrentValue({
    label:newValue,
    value:newValue
});
//try this code doing in useEffect
}, [])       

 useEffect(() => {
           getCurrentValue(currentValue.value);
           getSortOrder()
      },[currentValue]); //Everytime currentValue changes it will give new state

答案 1 :(得分:0)

之所以发生这种情况,是因为“ setCurrentValue”功能是一个异步功能,并且在“ getCurrentValue”和“ getSortOrder”功能均已完成执行后,状态会更新。

一个简单的解决方案是将参数'newValue'传递给这两个函数:

    const getTest = useCallback((newValue:string) => {
           setCurrentValue({
              label:newValue,
              value:newValue
             });
           getCurrentValue(newValue);
           getSortOrder(newValue)
     }, [])


     const getSortOrder  =(newValue) => {
        console.log(newValue);
      }

或者您也可以使用“ useEffect”功能在状态值更新后触发这些功能:

    const getTest = useCallback((newValue:string) => {
       setCurrentValue({
          label:newValue,
          value:newValue
         });
    }, [])

    useEffect(() => {
      getCurrentValue();
      getSortOrder()
    },[currentValue]);