简体   繁体   English

React Native datetimepicker 重新渲染回默认值

[英]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.在 React 中,每次调用组件 function 时都必须调用您使用的任何钩子,例如useStateuseMemo 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 :要解决此问题,请将您对useMemo的调用移出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.现在useMemo将被一致地调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM