React Hook 延迟了 useEffect 触发?

Rob*_*ton 6 reactjs react-hooks use-effect

我试图在我的反应钩子中使用 useEffect() 在我的道具改变时更新状态。但是有延迟,并且 useEffect 仅在我再次单击钩子中的元素后才触发。我对使用钩子相当陌生,任何帮助将不胜感激。谢谢

function ImageOrderSelect (props) {
  const [clicked, setClicked] = useState(false)
  const [options, setOptions] = useState(props.options)
  const [current, setCurrent] = useState(props.current)

  useEffect(() => {
      setCurrent(props.current)
    }, [props.current])


  if(!clicked){
    return (
        <div className="image-order-select-icon" onClick={() => setClicked(!clicked)}>
            <FontAwesomeIcon size="lg" icon={faCircle} />
            <p>{current}</p>
        </div>
    )
  } else if(clicked){
      return (
          <div className="image-order-select">
              {optionsList}
          </div>
      )
  }


}
Run Code Online (Sandbox Code Playgroud)

Abu*_*ail 7

    useEffect(() => {

      setTimeout(()=>{
       setCurrent(props.current)
      }, 1000)
  
    }, [props.current])
Run Code Online (Sandbox Code Playgroud)

您只需要在显示当前...

或最佳方法添加回调函数

useEffect(() => {

 
   setCurrent(() => props.current)
  

}, [props.current])
Run Code Online (Sandbox Code Playgroud)


Rob*_*ton 0

  let optionsList = options.map((option, index) => {
  return (
  <div key={index} onClick={() => {

      props.handleImageSort(option, props.index)
      setTimeout(() => {
          setClicked(!clicked)
      }, .500)
  }}>
    <p>{option}</p>
  </div>
  )
Run Code Online (Sandbox Code Playgroud)

})

问题是我试图同时调用 setClicked ,但由于某种原因阻止了它的调用。setTimeout 使它可以工作,尽管并不理想。如果有人有更好的解决方案,将会有兴趣听到。