反应挂钩状态:未定义

React hooks state : Undefined

这里是 React 的新手,正在努力学习基本的 useState 挂钩程序。创建了一个简单的功能组件,名为 CounterHooks,旨在制作一个简单的 +-1 计数器。

这是代码:

实际组件是这个

CounterHooks.js

    import React, { useState } from 'react'
    export default function CounterHooks({initialCount})  {
      const [count , setCount ] = useState(initialCount) 
      return (
        <div>
                <button onClick = {() =>   setCount(  prevCount => prevCount -1 ) }>-</button>
                 {count}
                <button onClick = {  () => setCount(prevCount => prevCount +1 ) } >+</button>
        </div>
    
      )
    }

渲染它的组件。 App.js

    import React from 'react';
    
    
    import CounterHooks from './CounterHooks'
    function App() {
      
      console.log("Render App")
      
      return (
        <>
        CounterHooks
        <CounterHooks intialCount = {0} />
        </>
    
      ) 
    }

export default App;

The output rendered is there in the image

当我尝试按下任何按钮时,输出变为 NaN。

请帮帮我,如果还需要任何其他必要的代码来进一步说明,请告诉我。

非常感谢。

您在传递 initialCount 道具时有错别字:

function App() {
  console.log("Render App");

  return (
    <>
      CounterHooks
      //            v not intialCount 
      <CounterHooks initialCount={0} />
    </>
  );
}

useState只初始化一次。当您将 initialCount 属性传递给 CounterHooks 组件并直接将其用于 useState 初始值时,当值 initialCount 更新为不是 undefined。因此 count 的状态始终保持 undefined.

您需要在此处使用 useEffect 以在 prop initialCount 的值更新时保持 count 的值同步。

import React, { useState } from 'react'
export default function CounterHooks({initialCount})  {
  const [count , setCount ] = useState(initialCount);

  useEffect(() => {
   setCount(initialCount) // update count after mount
  }, []);

  return (
      <div>
            <button onClick = {() =>   setCount(  prevCount => prevCount -1 ) 
        }>-</button>
             {count}
            <button onClick = {  () => setCount(prevCount => prevCount +1 ) } 
         >+</button>
    </div>

  )
}