我有下一个组件:
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleUserKeyPress = useCallback((event) => {
if (event.keyCode === 13) {
doLogin({ username, password }, loginDispatch, callback);
}
}, []);
useEffect(() => {
window.addEventListener('keypress', handleUserKeyPress);
}, [handleUserKeyPress]);
<ProjectFormField
label={t('email')}
formInputProps={{
value: username,
onChange: (event) => setUsername(event.target.value),
}}
inputType="email"
/>
<ProjectFormField
label={t('password')}
formInputProps={{
value: password,
onChange: (event) => setPassword(event.target.value),
}}
type="passwordField"
/>
<Button
label={'loginEnter'}
id="login-button"
disabled={ !username || !password}
onClick={() => {
doLogin({ username, password });
}}
/>
***ProjectFormField是我们为Material ui文本字段组件定制的应用程序包装器
当我点击按钮时,用户名和密码的值存在于状态中。当我按下回车按钮时,回调函数正在工作,但状态中的值为空。我还尝试了使用userRef的解决方案,其中ref是登录组件的包装容器,但结果是一样的。我做错了什么?
我今天遇到了同样的问题&上周有一次,我推迟了。看到这个问题&答复然后找到了这个github回复。
在那里我看到了一个关于如何使用useRef
的例子。我发现这让事情变得复杂。然而,在最后,他概述了如何将函数传递给setState
函数以更新值。效果很好!
在我的情况下是这样的:
const [posts, setPosts] = useState([]);
useEffect(function onLoad() {
const unregisterEventListener = listenToNewPostEvent();
return unregisterEventListener;
}, []);
function listenToNewPostEvent() {
function handleNewPost(post) {
// "posts" is empty in this line.
// Calling setPosts([post, ...posts]) always left "posts" with one entry.
// So, I changed as follows as mentioned in the previously given link.
setPosts(function updatePosts(posts) {
// Here "posts", which is coming as parameter to this function is the latest one.
return [post, ...posts];
});
// Now the posts array has the latest data & the same gets reflected in the screen as well.
}
return eventSystem.on(NEW_POST, handleNewPost);
}
您可能希望在此处使用useRef
挂钩。以下是您可以参考的codesandbox链接:https://codesandbox.io/s/exciting-framework-mprqg?file=/src/index.js