如何在组件外部访问React Context?

时间:2019-10-02 14:58:12

标签: reactjs

我正在尝试实现一个功能,该功能可以通过按钮从功能性React组件中调用。

应该从我自己的数据库中删除一个用户。但是我需要Firebase的访问令牌才能将此受保护的API调用到我的后端。

现在我正在通过Context API提供firebase实例,但是我似乎找不到从React Component外部访问该实例的方法。

我收到此错误:

  

第10行:希望进​​行赋值或函数调用,而是看到一个表达式

我是用错误的方式来处理这个问题吗?

import React from 'react';
import axios from 'axios';

import { PasswordForgetForm } from '../PasswordForgetForm/PasswordForgetForm';
import PasswordChangeForm from '../PasswordChangeForm/PasswordChangeForm';
import { AuthUserContext, withAuthorization } from '../../services/Session';
import { FirebaseContext } from '../../services/Firebase';

const deletUser = (authUser) => {
  {
    firebase => {
      const token = firebase.doGetIdToken();
      console.log(token);
      axios.delete('/api/users/' + authUser.uid, {
        headers: {
          authorization: `Bearer ${token}`
        }
      })
        .then(res => {
          //this.props.history.push('/dashboard');
          console.log(res);
        })
    }
  }

}

const AccountPage = () => (
  <AuthUserContext.Consumer>
    {authUser => (
      <div>
        <h1>Account: {authUser.email}</h1>
        <PasswordForgetForm />
        <PasswordChangeForm />
        <button type="button" onClick={() => deletUser(authUser)}>Delete Account</button>
      </div>
    )}
  </AuthUserContext.Consumer>
);

const condition = authUser => !!authUser;

export default withAuthorization(condition)(AccountPage);

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

代码声明一个匿名对象,内部语法不正确

 const deletUser = (authUser) => {
  {//anonymous   object
    firebase => {//There is no key for the member of the object
      const token = firebase.doGetIdToken();
      console.log(token);
      axios.delete('/api/users/' + authUser.uid, {
        headers: {
          authorization: `Bearer ${token}`
        }
      })
        .then(res => {
          //this.props.history.push('/dashboard');
          console.log(res);
        })
    }
  }//You never call or return anything of your object 

}