TypeError:无法解构“ this.props”的属性“凭证”,因为它未定义

时间:2020-07-27 03:35:09

标签: javascript reactjs firebase redux google-cloud-firestore

用户名属性显示为undefined。它在currentUser下的凭据下显示为状态,因此我不确定为什么会这样。错误显示在:

const {
   classes,
   currentUser: {
     credentials: { username, image },
     loading,
     authenticated,
   },
  } = this.props;

完整代码:

class messages extends Component {
  constructor() {
    super();
    this.state = {
      selectedChat: null,
      newChatFormVisible: false,
      chats: [],
    };
  }

  selectChat = (chatIndex) => {
    ...};

  newChatBtnClicked = () => {
    ...};

  render() {
    const {
      classes,
      currentUser: {
        credentials: { username, image },
        loading,
        authenticated,
      },
    } = this.props;

    firebase
      .firestore()
      .collection("chats")
      .where("users", "array-contains", username)
      .onSnapshot(async (res) => {
        const chats = res.docs.map((_doc) => _doc.data());
        await this.setState({
          chats: chats,
        });
        console.log(this.state);
      });

    let messagesMarkup = !loading ? (
      authenticated ? (
        <div>
          <div>Open Messages</div>
          <ChatList
            history={this.props.history}
            newChatBtn={this.newChatBtnClicked}
            selectChat={this.selectedChat}
            username={username}
            selectedChatIndex={this.state.selectedChat}
          ></ChatList>
        </div>
      ) : (
        <Redirect to="/login" />
      )
    ) : (
      <p> loading...</p>
    );
    return messagesMarkup;
  }
}

messages.propTypes = {
  currentUser: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
  credentials: state.currentUser.credentials,
});

export default connect(mapStateToProps)(messages);

我试过没有任何运气的凭据。用户名。我究竟做错了什么?我是否缺少mapStateToProps?我想获取currentUser,以便我可以显示他们的所有聊天消息,并且其用户名位于currentUser下的凭据下

1 个答案:

答案 0 :(得分:1)

credentials恰好是undefined,因此js无法解构

您可以:

a-通过以下方式设置其默认值:

    const {
      classes,
      currentUser: {
        credentials: { username, image } = { username: 'foo', image: 'bar' },
        loading,
        authenticated,
      },
    } = this.props;

b-通过使用currentUser破坏对象的上游,将每个<messages {...currentUser}>属性作为道具传递,并使用messages.defaultProps = { credentials: { username: 'foo', image: 'bar' }}或在您定义了[零件。这可以看作是比较惯用的

c-确保在使用组件^^

时,defaultProps永远不会credentials