如何将函数从 FUNCTIONAL 传递到 CLASS 组件并在渲染之外访问它(没有 prop ),在 React js 中使用上下文?

How to pass function from FUNCTIONAL to CLASS component and access it outside of render( without prop ), using context in react js?

如何在 React js 中使用上下文将 function 从 FUNCTIONAL 传递到 CLASS 组件?

我的代码:

上下文:

authContext.js

import React from 'react'
const AuthContext = React.createContext()
export const AuthProvider = AuthContext.Provider
export const AuthConsumer = AuthContext.Consumer
export default AuthContext

功能组件:

App.js

...
import AuthPage from './pages/AuthPage';
import { AuthProvider } from './components/Context/authContext'

function App(props) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  const checkAuthenticated = async () => {
    //console.time('fetch')

    try {
      const res = await fetch("http://localhost:4000/api/verify", {
        method: "POST",
        headers: { jwt_token: localStorage.token }
      });

      const parseRes = await res.json();
      parseRes === true ? setIsAuthenticated(true) : setIsAuthenticated(false);
    } catch (err) {
      console.error(err.message);
    }
    //console.timeEnd('fetch')

  };

  const setAuth = boolean => {
    setIsAuthenticated(boolean);
  };


  useEffect(() => {
    checkAuthenticated();
  }, [isAuthenticated, setAuth]);


  return (
    <Fragment>
      <BrowserRouter basename={'/'}>
        <GAListener>
          <Switch>
            <LayoutRoute
              exact
              path="/login"
              layout={EmptyLayout}
              component={props => (
                <AuthProvider value={{ setAuth: setAuth }}>
                  <AuthPage {...props} authState={STATE_LOGIN} />
                </AuthProvider>
              )}
            />
            <Redirect to="/" />
          </Switch>
        </GAListener>
      </BrowserRouter>

    </Fragment>
  )
}

export default App;

CLASS 分量:

AuthForm.js

import AuthContext from '../components/Context/authContext'

class AuthForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      usernameInput: '',
      emailInput: '',
      passwordInput: '',
      confirmPasswordInput: '',
      remeberMe: false,
      agreeTerms: false,
      toDashboard: false
    };
  }

  componentDidMount() {
    if (localStorage.token) {
      this.setState(() => (
        {
          toDashboard: true
        }
      ))
    }
  }
  componentDidUpdate() {
      **// I WANT TO ACCESS THE 'setAuth' function here**
  }

  render() {
    return (
        <div>
            //Some code
        </div>
    );
  }
}

export default AuthForm;

使用 AuthForm.js(class 组件)中的 setAuth 函数,我想更改 App.js(功能组件)中的 isAuthenticated 值。 所以,基本上我想在 componentDidUpdate() 中访问 setAuth。

从 class 组件访问 Context 的最常见方法是通过 static contextType。如果您需要渲染之外的上下文中的值,或者在生命周期方法中,您将以这种方式使用它。

import React from "react";
import AuthContext from "./context";

class AuthForm extends React.Component {
  constructor(props) {
      ...
  }
  static contextType = AuthContext

  componentDidUpdate() {
    const {setAuth} = this.context
    // Access the 'setAuth' function here
  }

  render() {
    return <div>Some code</div>;
  }
}

export default AuthForm;

在@gemhar 的帮助下解决了问题

将在 AuthForm.js

中进行更改
...
import AuthContext from '../components/Context/authContext'

class AuthForm extends React.Component {

  //Add this line
  static contextType = AuthContext;

  constructor(props) {
    super(props);
    this.state = {
      usernameInput: '',
      emailInput: '',
      passwordInput: '',
      confirmPasswordInput: '',
      remeberMe: false,
      agreeTerms: false,
      toDashboard: false
    };
  }

  componentDidMount() {
    if (localStorage.token) {
      this.setState(() => (
        {
          toDashboard: true
        }
      ))
    }
  }
  componentDidUpdate() {
      //I can access setAuth here
      this.context.setAuth(true)

      //or by destructuring
      let {setAuth} = this.context;
      setAuth(true)
  }

  render() {
    return (
        <div>
            //Some code
        </div>
    );
  }
}

export default AuthForm;