React JS JSX,无法理解在无状态函数中传入参数的回调的用处

React JS JSX, can't understand the usefulness of a callback passed in param inside a statless function

我正在使用 React Router 6 开发 REACT JS 项目。 我正在尝试使用 React Context 来处理身份验证。

在这个例子中:

const fakeAuthProvider = {
  isAuthenticated: false,
  signin(callback) {
    fakeAuthProvider.isAuthenticated = true;
    setTimeout(callback, 100); // fake async
  },
  signout(callback) {
    fakeAuthProvider.isAuthenticated = false;
    setTimeout(callback, 100);
  },
};

export { fakeAuthProvider };

  let signin = (newUser, callback) => {
    return fakeAuthProvider.signin(() => {
      setUser(newUser);
      callback(); // why the passed callback is called here ?
    });
  };

  let signout = (callback) => {
    return fakeAuthProvider.signout(() => {
      setUser(null);
      callback(); // why the passed callback is called here ?
    });
  };

我不明白为什么回调在那边被调用,明知它没有在某处声明?

如果有人向我解释,我将不胜感激

您指的回调不是您在 fakeAuthProvider 对象方法中传递的回调。

在那里调用它意味着当用户登录或注销并且需要做一些事情时,将其作为回调传递。

例如,如果您想显示用户已登录的消息,您可以传递一个函数来代替 signinCallback,该函数将在用户登录后立即执行。

看看下面的代码。

const fakeAuthProvider = {
  isAuthenticated: false,
  fakeAuthSignin(fakeAuthCallback) {
    fakeAuthProvider.isAuthenticated = true;
    setTimeout(fakeAuthCallback, 100); // fake async
  },
  fakeAuthSignout(fakeAuthCallback) {
    fakeAuthProvider.isAuthenticated = false;
    setTimeout(fakeAuthCallback, 100);
  },
};

export { fakeAuthProvider };

let signin = (newUser, signinCallback) => {
  // the arrow function that you are passing in 'fakeAuthProvider.fakeAuthSignin' is 'fakeAuthCallback'
  return fakeAuthProvider.fakeAuthSignin(() => {
    setUser(newUser);
    signinCallback(); // this is a callback which you will pass in 'signin' function. It will get executed once user is authorized.
  });
};

let signout = (signoutCallback) => {
  // the arrow function that you are passing in 'fakeAuthProvider.fakeAuthSignout' is fakeAuthCallback
  return fakeAuthProvider.fakeAuthSignout(() => {
    setUser(null);
    signoutCallback(); // this is a callback which you will pass in 'signout' function
  });
};