如何使用useState批量更新多个状态

时间:2020-04-20 19:46:03

标签: reactjs react-native

在常规反应中,通常会在onChange函数中像这样

批处理状态更新
_onChange:function(){
this.setState({
    date: new Date(),
    setShowDatepicker: false()
})

}

我正在尝试找出如何在功能反应中批处理状态更新

  const [date, setDate] = useState();
  const [showDatePicker, setShowDatepicker] = useState(false);

  const onChangeDate = (event, selectedDate) => {
     const currentDate = selectedDate || date;
     setDate(currentDate); //want to batch this will the setState below
     setShowDatepicker(false);
  };

每次设置状态时,都会导致重新渲染,从而影响行为。在文档中看不到解决方案。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您可以创建放置日期并将setShowDatePicker设置为单个useState


const [dateValues, setDateValues] = useState({
    date: new Date(),
    setShowDatepicker: false
});

const onChangeDate = (event, selectedDate) => {
  const currentDate = selectedDate || date;

  setDateValues({
      date: currentDate,
      setShowDatepicker: false
  })
};