Я не могу понять, почему я получаю следующую ошибку "Ошибка: недопустимый тип элемента:" - PullRequest
0 голосов
/ 08 января 2020

Я довольно новичок в React и еще новее в Firebase. Я следую учебному пособию Робина Виеруха по использованию React с Firebase. Ясно, что я сделал что-то не так, но это ускользает от меня. Я использую шаблон использования папок для именования своих компонентов индексным файлом. js в каждой папке компонентов для хранения кода.

Вот индекс. js для компонента приложения:

import React from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'

import * as ROUTES from '../../constants/routes'

import Navigation from '../Navigation'
import LandingPage from '../Landing'
import SignUpPage from '../SignUp'
import SignInPage from '../SignIn'
import PasswordForgetPage from '../PasswordForget'
import HomePage from '../Home'
import AccountPage from '../Account'
import AdminPage from '../Admin'

const App = () => (
  <Router>
    <Navigation />

    <hr />

    <Route exact path={ROUTES.LANDING} component={LandingPage} />
    <Route path={ROUTES.SIGN_UP} component={SignUpPage} />
    <Route path={ROUTES.SIGN_IN} component={SignInPage} />
    <Route path={ROUTES.PASSWORD_FORGET} component={PasswordForgetPage} />
    <Route path={ROUTES.HOME} component={HomePage} />
    <Route path={ROUTES.ACCOUNT} component={AccountPage} />
    <Route path={ROUTES.ADMIN} component={AdminPage} />
  </Router>
)

export default App

Вот индексный файл. js для компонента SignUp

import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { compose } from 'recompose'

import FirebaseContext, { withFirebase } from '../Firebase'
import * as ROUTES from '../../constants/routes'

const SignUpPage = () => (
  <div>
    <h1>SignUp</h1>
    <FirebaseContext.Consumer>
      { firebase => <SignUpForm firebase={firebase} />}
    </FirebaseContext.Consumer>
  </div>
)

...

export default SignUpPage

export { SignUpForm, SignUpLink }

Я не уверен, что другие файлы будут полезны.

Я приношу свои извинения , Кажется, я забыл самый важный файл. Вот индекс. js из папки sr c:

import React from 'react'
import ReactDOM from 'react-dom'

import './index.css'
import * as serviceWorker from './serviceWorker'

import App from './components/App'
import Firebase, { FirebaseContext } from './components/Firebase'

ReactDOM.render(
    // make Firebase Context available to the app
    <FirebaseContext.Provider value={ new Firebase() }>
      <App />
    </FirebaseContext.Provider>, 
    document.getElementById('root'),
  )

Ошибка, по-видимому, в строке 12 этого файла ReactDOM.render.

По запросу от @Victor Вот компоненты Firebase:

index. js из папки Firebase

import FirebaseContext, { withFirebase } from './context'
import Firebase from './firebase'

export default Firebase

export { FirebaseContext, withFirebase }

context. js из папки Firebase

import React from 'react'

const FirebaseContext = React.createContext(null)

// create the HOC withFirebase
export const withFirebase = Component => props => (
  <FirebaseContext.Consumer>
    { firebase => <Component { ...props } firebase={ firebase } />}
  </FirebaseContext.Consumer>
)

export default FirebaseContext

firebase. js из папки Firebase

import app from 'firebase/app'
import 'firebase/auth'
// import 'firebase/database'

// the constant value when the environment = 'production'
const prodConfig = {
  apiKey: process.env.REACT_APP_API_KEY,
  authDomain: process.env.REACT_APP_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_DATABASE_URL,
  projectId: process.env.REACT_APP_PROJECT_ID,
  storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_SENDER_ID,
}

// the constant value when the environment !== 'production'
const devConfig = {
  apiKey: process.env.REACT_APP_API_KEY,
  authDomain: process.env.REACT_APP_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_DATABASE_URL,
  projectId: process.env.REACT_APP_PROJECT_ID,
  storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_SENDER_ID,
}

// set the config constant to the appropriate value
const config = process.env.NODE_ENV === 'production' ? prodConfig : devConfig

class Firebase {
  constructor() {
    // initialize the app with the Firebase config
    app.initializeApp(config)

    this.auth = app.auth()
  }

  // ***** Auth API ***** (use the offical Firebase endpoint)
  doCreateUserWithEmailAndPassword = ( email, password ) => this.auth.createUserWithEmailAndPassword( email, password )

  // ***** SignIn ***** (use the offical Firebase endpoint)
  doSignInWithEmailAndPassword = ( email, password ) => this.auth.SignInWithEmailAndPassword( email, password )

  // ***** SignIn ***** (use the offical Firebase endpoint)
  doSignInWithEmailAndPassword = ( email, password ) => this.auth.SignInWithEmailAndPassword( email, password )

  // ***** SignOut ***** (use the offical Firebase endpoint)
  doSignOut = ( email, password ) => this.auth.SignOut()

  // ***** Password Reset ***** (use the offical Firebase endpoint)
  doPasswordReset = email => this.auth.sendPasswordResetEmail( email )

  // ***** Password Update ***** (use the offical Firebase endpoint)
  doPasswordUpdate = password => this.auth.currentUser.updatePassword( password )
}

export default Firebase

Надеюсь, что это делает.

1 Ответ

0 голосов
/ 09 января 2020

OK! Я понял. Проблема заключалась в том, что я пытался выставить FirebaseContext.Consumer в двух местах, в контексте. js файл в папке Firebase (который находится в этом приложении). Но я оставил код, раскрывающий FirebaseContext.Consumer, в блоке SignUpPage в файле index. js, а также в папке SignUp (именно там я его и поместил - до того, как я построил HO C (контекст. js). После того, как я смотрел на нее (но на самом деле не видел ее) в течение полутора дней, меня осенило, что я пытаюсь взять на себя двойную обязанность. Решением было реорганизовать SignUpPage следующим образом (сравните с моим предыдущим постом выше). ):

index. js для компонента SignUp:

import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { compose } from 'recompose'

import { withFirebase } from '../Firebase'
import * as ROUTES from '../../constants/routes'

const SignUpPage = () => (
  <div>
    <h1>SignUp Page</h1>
    <SignUpForm />
  </div>
)

...

const SignUpForm = compose(withRouter, withFirebase,)(SignUpFormBase)

export default SignUpPage

export { SignUpForm, SignUpLink }

Спасибо всем, кто внес свой вклад в мой мыслительный процесс.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...