【问题标题】:How state initialization works in React?React 中的状态初始化是如何工作的?
【发布时间】:2021-06-17 14:57:12
【问题描述】:

我有一个名为 inputValue 的本地状态的主要组件将在 onChange 事件发生时更新。在我的主要组件中并调用 customHook,这个自定义钩子将接收 inputValue 作为参数。

在我的自定义钩子中,我使用 useState 声明另一个名为 customValue 的本地状态并初始化为从我的主组件接收的 inputValue。在第一次渲染后,当我尝试访问 customValue 的值时,它没有给我来自 inputValue 的最新值,它一直只给我它初始化的值。

我的部分主要组件代码:

const[inputValue, setInputValue] = useState("hi");

const onChange = () => {
  e.preventDefault();
  setInputValue(e.target.value)
};

const value = useCustomHook(inputValue);

我的自定义钩子:

    export default function useCustomHook(inputValue){
      const[customValue, setCustomValue] = useState(inputValue);
    
      return console.log(customValue);
   };
// It always returns "hi", besides it gest called in each re-reder of the main component. 

我知道要解决这个问题,我需要这样做

setCustomValue(inputValue)

所以我的问题是...... customValue 不应该在我的主要组件的每次重新渲染中自动初始化为来自 inputValue 的最新值? p>

【问题讨论】:

    标签: reactjs use-state


    【解决方案1】:

    您应该将事件侦听器传递给您的事件处理函数,例如:

    const onChange = e => {
      e.preventDefault();
      setInputValue(e.target.value)
    };
    

    【讨论】:

      猜你喜欢
      • 2019-01-04
      • 2016-12-29
      • 2017-10-11
      • 2018-07-23
      • 2022-12-06
      • 2019-05-08
      • 1970-01-01
      • 2018-08-22
      • 2021-07-09
      相关资源
      最近更新 更多