【发布时间】: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>
【问题讨论】: