React中的状态初始化是如何工作的



我有一个主组件,当onChange事件发生时,它的本地状态被称为inputValue。在我的主组件中,同时调用customHook,这个自定义钩子将接收inputValue作为参数。

在我的自定义钩子中,我使用useState声明了另一个名为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

您应该向事件处理程序函数传递一个事件侦听器,如:

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

最新更新