简体   繁体   English

React state 值在本机事件的回调中为空

[英]React state values are empty inside callback from native event

I have next component:我有下一个组件:

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 });
        }}
        
      />

     

***Where ProjectFormField is our custom app wrapper for Material ui text field component ***其中 ProjectFormField 是我们的 Material ui 文本字段组件的自定义应用程序包装器

When I do click on button the values of username and password exists in state.当我单击按钮时,用户名和密码的值存在于 state 中。 When I press the enter button, the callback function is working, but values in state are empty.当我按下回车按钮时,回调 function 正在工作,但 state 中的值是空的。 I also tried solution with userRef, where the ref was the wrapper container of login component, but the result was the same.我还尝试了 userRef 的解决方案,其中 ref 是登录组件的包装容器,但结果是一样的。 What I am doing wrong?我做错了什么?

you might want to use useRef hook here.你可能想在这里使用useRef钩子。 Here is the codesandbox link you can refer: https://codesandbox.io/s/exciting-framework-mprqg?file=/src/index.js这是您可以参考的代码框链接: https://codesandbox.io/s/exciting-framework-mprqg?file=/src/index.js

I was having the same issue today & once in the last week, which I postponed.我今天和上周有一次同样的问题,我推迟了。 Saw this question & answer.看到这个问题和答案。 Then found this github reply .然后找到这个github 回复

There I saw an example about how useRef can be used.在那里我看到了一个关于如何使用useRef的例子。 I found it as making things complex.我发现它使事情变得复杂。 However, in the end he outlines about passing a function to setState function to update the values.但是,最后他概述了将 function 传递给setState function 以更新值。 It worked great!效果很好!

In my case it was like this:就我而言,它是这样的:

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);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应本机Webview事件侦听器将空事件对象传递给回调 - react native webview event listener passes empty event object to callback 从回调中反应本机更改 state - React native change state from callback 为什么在回调函数中反应状态(数组)为空? 为什么不使用来自外部范围的更新值? - Why is react state(array) empty inside callback function? Why is it not using the updated value from outer scope? 无法在事件回调函数的 socketio 中使用反应状态 - Can't use react state inside a socketio on event callback function 反应钩子没有从库事件(FabricJS)的回调 function 中返回更新的 state 值 - React hooks not returning updated state values inside callback function from library events (FabricJS) 为什么更新的 state 没有反映在事件侦听器中:React Native,Hooks - why updated state not reflected inside an event listener: React Native, Hooks 从内部回调函数在React Native中调用this.setState() - Call this.setState() in React Native from Inside Callback Function React-Native:无法从表单值设置状态 - React-Native: Cannot set state from form values React Native-为什么这个状态对象在功能上是空的? - React Native - Why is this state object empty in function? React Native State 未使用空数组进行更新 - React Native State not updating with an empty Array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM