我正在使用react.js,并且我有以下代码。


function App() {
  let Submitable;
  const [values, setValues] = useState([])

 //...



  onTicket.save = () => {
    console.log(Submitable) // logs undefiened
    if (Submitable) {
      return true
    } else {
      return `Please fill out the following fields before submitting:${values.map(el => ` ${el.name}`)}`
    }
  })

  useEffect(() => {
    if (values.length === 0) {
      Submitable = true
      //enableSave
    } else {
      Submitable = false
      //disableSave
    }
  }, [values])

  return (
    <>
      ///jsx code block
    </>
  );
}

export default App;


我认为在useEffect函数将Submitable设置为true或false时,该值将携带到其他函数中,但是在调用时,Submitable日志未定义。如果我尝试将Submitable作为参数传递,它也会记录未定义的内容。

最佳答案

useEffect内部的分配将在每次渲染时丢失。要随时间保留值,请将其存储在useRef挂钩中,并将可变值保留在current属性内

const Component = () =>{
    const submitable = useRef()

    useEffect(() =>{
        submitable.current = 'foo'
    },[])

    console.log(submitable.current) // 'foo'
}

07-21 21:17