简体   繁体   English

在 reactjs 中使用带有 useState 钩子的回调

[英]use callback with useState hook in reactjs

i'm trying to update the user info on my database on the handleChange function every time there is a new change but the problem that im facing is that i have to to wait for the setdata till it finish then updateUserInfo how i can solve that我试图在每次有新更改时更新我的数据库上的用户信息handleChange function 但我面临的问题是我必须等待 setdata 直到它完成然后 updateUserInfo 我如何解决这个问题

  const [mydata, setData] = useState({
    user_gender: "",
    user_relationship: "",
    user_birth_day: "",
    user_birth_month: "",
    user_gender_interest: "",
    user_birth_year: "",
    user_interests: {
      dancing: false,
      family: false,
      art: false,
      photography: false,
      friends: false,
      travel: false
    }
  });

const handleChange = event => {
    setData({
      ...mydata,
      [event.target.name]: event.target.value
    });
    async function update() {
      await updateUserInfo(mydata[event.target.name], stableDispatch);
    }
    update();
  };

Call updateUserInfo() as a callback.调用 updateUserInfo() 作为回调。

You can pass a function as a 2nd parameter to setState() which will automatically be called when the state is set.您可以将 function 作为第二个参数传递给 setState(),在设置 state 时将自动调用该参数。

useEffect(() => {
  updateUserInfo(mydata[event.target.name], stableDispatch));
}, [mydata]);

The solution here is to copy the state in a variable which you can use to update state and the userInfo这里的解决方案是将 state 复制到一个变量中,您可以使用它来更新 state 和 userInfo

const handleChange = event => {

    const data = {
      ...mydata,
      [event.target.name]: event.target.value
    }
    setData(data);
    async function update() {
      await updateUserInfo(data[event.target.name], stableDispatch);
    }
    update();
  };

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM