当前位置: 首页 > 知识库问答 >
问题:

元素类型无效:应为字符串或类/函数(对于复合组件),但得到:对象

宰父跃
2023-03-14

我正在做一些关于React的教程。js和我对这是相当陌生的。我在仪表板上有这个代码。js

import React from 'react';
import NewChatComponent from '../newChat/newChat';
import ChatListComponent from '../chatList/chatList';
import ChatViewComponent from '../chatView/chatView';
import ChatTextBoxComponent from '../chatTextBox/chatTextBox';
import styles from './styles';
import { Button, withStyles } from '@material-ui/core';
const firebase = require("firebase");

class DashboardComponent extends React.Component {

  constructor() {
    super();
    this.state = {
      selectedChat: null,
      newChatFormVisible: false,
      email: null,
      friends: [],
      chats: []
    };
  }

  render() {

    const { classes } = this.props;

    if(this.state.email) {
      return(
        <div className='dashboard-container' id='dashboard-container'>
          <ChatListComponent history={this.props.history} 
            userEmail={this.state.email} 
            selectChatFn={this.selectChat} 
            chats={this.state.chats} 
            selectedChatIndex={this.state.selectedChat}
            newChatBtnFn={this.newChatBtnClicked}>
          </ChatListComponent>
          {
            this.state.newChatFormVisible ? null : <ChatViewComponent 
              user={this.state.email} 
              chat={this.state.chats[this.state.selectedChat]}>
            </ChatViewComponent>
          }
          { 
            this.state.selectedChat !== null && !this.state.newChatFormVisible ? <ChatTextBoxComponent userClickedInputFn={this.messageRead} submitMessageFn={this.submitMessage}></ChatTextBoxComponent> : null 
          }
          {
            this.state.newChatFormVisible ? <NewChatComponent goToChatFn={this.goToChat} newChatSubmitFn={this.newChatSubmit}></NewChatComponent> : null
          }
          <Button onClick={this.signOut} className={classes.signOutBtn}>Sign Out</Button>
        </div>
      );
    } else {
      return(<div>LOADING....</div>);
    }
  }

  signOut = () => firebase.auth().signOut();

  submitMessage = (msg) => {
    const docKey = this.buildDocKey(this.state.chats[this.state.selectedChat]
      .users
      .filter(_usr => _usr !== this.state.email)[0])
    firebase
      .firestore()
      .collection('chats')
      .doc(docKey)
      .update({
        messages: firebase.firestore.FieldValue.arrayUnion({
          sender: this.state.email,
          message: msg,
          timestamp: Date.now()
        }),
        receiverHasRead: false
      });
  }

  // Always in alphabetical order:
  // 'user1:user2'
  buildDocKey = (friend) => [this.state.email, friend].sort().join(':');

  newChatBtnClicked = () => this.setState({ newChatFormVisible: true, selectedChat: null });

  newChatSubmit = async (chatObj) => {
    const docKey = this.buildDocKey(chatObj.sendTo);
    await 
      firebase
        .firestore()
        .collection('chats')
        .doc(docKey)
        .set({
          messages: [{
            message: chatObj.message,
            sender: this.state.email
          }],
          users: [this.state.email, chatObj.sendTo],
          receiverHasRead: false
        })
    this.setState({ newChatFormVisible: false });
    this.selectChat(this.state.chats.length - 1);
  }

  selectChat = async (chatIndex) => {
    await this.setState({ selectedChat: chatIndex, newChatFormVisible: false });
    this.messageRead();
  }

  goToChat = async (docKey, msg) => {
    const usersInChat = docKey.split(':');
    const chat = this.state.chats.find(_chat => usersInChat.every(_user => _chat.users.includes(_user)));
    this.setState({ newChatFormVisible: false });
    await this.selectChat(this.state.chats.indexOf(chat));
    this.submitMessage(msg);
  }

  // Chat index could be different than the one we are currently on in the case
  // that we are calling this function from within a loop such as the chatList.
  // So we will set a default value and can overwrite it when necessary.
  messageRead = () => {
    const chatIndex = this.state.selectedChat;
    const docKey = this.buildDocKey(this.state.chats[chatIndex].users.filter(_usr => _usr !== this.state.email)[0]);
    if(this.clickedMessageWhereNotSender(chatIndex)) {
      firebase
        .firestore()
        .collection('chats')
        .doc(docKey)
        .update({ receiverHasRead: true });
    } else {
      console.log('Clicked message where the user was the sender');
    }
  }

  clickedMessageWhereNotSender = (chatIndex) => this.state.chats[chatIndex].messages[this.state.chats[chatIndex].messages.length - 1].sender !== this.state.email;

  componentWillMount = () => {
      firebase.auth().onAuthStateChanged(async _usr => {
        if(!_usr)
          this.props.history.push('/login');
        else {
          await firebase
            .firestore()
            .collection('chats')
            .where('users', 'array-contains', _usr.email)
            .onSnapshot(async res => {
              const chats = res.docs.map(_doc => _doc.data());
              await this.setState({
                email: _usr.email,
                chats: chats,
                friends: []
              });
            })
        }
    });
  }
}

export default withStyles(styles)(DashboardComponent);

有问题的代码行如下:-

newChatBtnClicked = () => this.setState({ newChatFormVisible: true, selectedChat: null });

如果我设置newChatFormbVisible:false,我不会得到错误,但是将其设置为true会失败,并出现以下错误:-

指数js:1375警告:反应。createElement:type无效--应为字符串(对于内置组件)或类/函数(对于复合组件),但应为Get:object。您可能忘记了从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

在仪表板上检查代码。js:47。在BrowserRouter(src/index.js:24)控制台中的路由器(BrowserRouter创建)中的div(src/index.js:25)中的路由(src/index.js:28)中的WithStyles(DashboardComponent)(由Context.Consumer创建)中的DashboardComponent(由WithStyles(DashboardComponent)中指数js:1375警告@react。发展js:188警告@react。发展js:623 createElementWithValidation@react。发展js:1785 render@dashboard。js:44 finishClassComponent@react-dom。发展js:15319 updateClassComponent@react-dom。发展js:15274 beginWork@react-dom。发展js:16262 performUnitOfWork@react-dom。发展js:20279 workLoop@react-dom。发展js:20320 renderRoot@react-dom。发展js:20400 performworkroot@react-dom。发展js:21357 performWork@react-dom。发展js:21267 performSyncWork@react-dom。发展js:21241 interactiveUpdates$1@react dom。发展js:21526 interactiveUpdates@react-dom。发展js:2268 dispatchInteractiveEvent@react-dom。发展js:5085。发展js:57未捕获不变冲突:元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。您可能忘记了从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

共有1个答案

广宏远
2023-03-14

我只是在评论部分与@Johann讨论后写下这个答案。因此,如果其他人遇到相同类型的错误,他们会更容易看到

好的,我不确定,但您可以尝试使用带有自动关闭标记的组件,如

 类似资料: