React Hook延迟使用效果触发?

时间:2019-09-04 12:46:32

标签: reactjs react-hooks use-effect

我正在尝试在我的react挂钩中使用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>
      )
  }


}

3 个答案:

答案 0 :(得分:3)

    useEffect(() => {

      setTimeout(()=>{
       setCurrent(props.current)
      }, 1000)

    }, [props.current])

您只需要在显示当前...之前添加超时/延迟...

答案 1 :(得分:1)

我不确定您要达到什么预期的效果,但是这里有一些经过整理的代码。也许会对您有进一步的帮助。

function ImageOrderSelect ({ current, options ) { // deconstruct here to save code
  const [clicked, setClicked] = useState(false);
  // you dont have to keep additional state since props is a state.
  useEffect(() => {
    setTimeout(() => {
      // do something here 1 sec after current has changed
    }, 1000);
  }, [current]);

  useEffect(() => {
    setTimeout(() => {
       // do something 1 sec after clicked has changed
    }, 1000);
  }, [clicked]);

  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>
      )
  }
}

如果您要在最后一次单击图像后1秒触发效果,则必须重置每次单击的超时,直到超时。这是对用户交互产生任何延迟影响的常见做法:

let timeout;

useEffect(() => {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
     // do something 1 sec after a click is done
     // but dont do anything if another click happened before 1sec of the previous 
     // click has expired
  }, 1000);
}, [clicked]);

如果您可以提供更详细的代码示例以及所需UI效果的更深入说明,我可以为您提供明确的帮助。

答案 2 :(得分: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>
  )

})

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