简体   繁体   中英

React Native datetimepicker re-renders back to default value

I am trying to implement this solution found here but I am running into the following error. Error: rendered more hooks than during the previous render

Here is my code. What am I missing? Am I implementing the solution correctly?

export default function Foo(){
const [showCalendar, setShowCalendar] = useState(false);

   function fooA(newDate){
      onChange(newDate)// function that updates date, works on ios. I do not think its the issue.
    setShowCalendar(false)

   }

   function fooB(){
     {React.useMemo(() => {
        return (
          <RNDateTimePicker 
            onChange={fooA(newDate)} 
            value={date} 
            display='spinner' 
            {...rest} 
          />
        )
      }, [showCalendar])}
   }

   return (
      <TouchableOpacity onPress={() => setShowCalendar(true)}>
        fooB()
      </TouchableOpacity>
   )
}

In React, any hooks that you use, such as useState or useMemo , must be invoked every time your component function is invoked. If a hook is conditionally called, or if there's any other scenario where the hook doesn't always get called, you get the error that you're seeing. To fix this, move your call to useMemo out of fooB :

const fooB = React.useMemo(() => {
        return (
          <RNDateTimePicker 
            onChange={fooA(newDate)} 
            value={date} 
            display='spinner' 
            {...rest} 
          />
        )
      }, [showCalendar]);

   return (
      <TouchableOpacity onPress={() => setShowCalendar(true)}>
        {fooB}
      </TouchableOpacity>

Now useMemo will be invoked consistently.

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