无法在具有功能的上下文提供程序中使用State

时间:2019-05-05 20:28:24

标签: reactjs react-hooks react-context

我整天都在挣扎..我想重构挂钩和上下文,如何在Provider值内使用useState-Function?

基于类的所有东西都工作正常,现在我无法重构它。

import React, { useState } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import AuthContext from './context/auth-context';

const App = () => {

const [token, setToken] = useState('');
const [userId, setUserId] = useState('');

const login = (token, userId) => {
  setToken(token);
  setUserId(userId);
};



return (

  <BrowserRouter>
    <AuthContext.Provider value={{login: login}} >
      <Switch>
        <Route ..... />
        <Route ..... component={SignIn}/>
      </Switch>
    </AuthContext.Provider>
  </BrowserRouter>
);
};

export default App;


/// Other File 

import React, { useState, useContext } from 'react';
import AuthContext from './context/auth-context';

const SignIn () => {

const context = useContext(AuthContext);

// some Database-Stuff with the following results:
// resData.data.login.token = token
// resData.data.login.userId = userId
// i want to execute the login function from the App and set the state 
// to the values.

context.login(resData.data.login.token, resData.data.login.token);

};

目标:context.login执行App-Component中的功能并将状态设置为令牌= resData.dada.login.token的值和userId = value resData.data.login.userId的值

0 个答案:

没有答案