【问题标题】:why I'm getting the value of ID as Undefined in the below code?react为什么我在下面的代码中将 ID 的值设为未定义?反应
【发布时间】:2020-08-18 23:15:18
【问题描述】:

//当我试图在每次我得到未定义时控制 id 时。我相信它在范围内,但我仍然未定义

function App() {
  let id;

  let [time, settime] = useState('');

  function timechnage() {

    id = setInterval(() => {
      settime(Date);
    }, 1000);

  }


  function timecage() {
    console.log(id);

    console.log(id);

    settime(0);
  }

  return (

    <div>
      <p>time is {time}</p>
      <button onClick={timechnage}>start</button>
      <button onClick={timecage}>reset</button> 
    </div>
  )
}

export default App;

【问题讨论】:

  • 我认为它超出了范围。在函数 timechange 中尝试 Console.log
  • 在 timechange 函数中我得到了 id 值,但是为什么我没有在 timecage 函数中得到 id 的值
  • 范围由花括号定义,在花括号之外

标签: reactjs react-redux react-router react-hooks


【解决方案1】:

id 会在每次组件更新时重新创建,因此它之前的值会丢失。

要在组件的生命周期内保留id 的值,您需要将其放入ref

// Create the ref
const id = useRef();

// Assign it
id.current = setInterval(...

// Display it
console.log(id.current)

【讨论】:

  • 知道了。非常感谢你
猜你喜欢
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多