【问题标题】:TypeError: Cannot destructure property 'credentials' of 'this.props' as it is undefinedTypeError:无法解构“this.props”的属性“凭据”,因为它未定义
【发布时间】:2020-07-27 03:35:09
【问题描述】:

用户名属性未定义。它显示在 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);

我尝试了 credentials.username,但没有成功。我究竟做错了什么?我是否缺少 mapStateToProps 的某些内容?我想获取 currentUser 以便我可以显示他们所有的聊天消息,并且他们的用户名在 currentUser 下的凭据下

【问题讨论】:

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


    【解决方案1】:

    credentials恰好是undefined所以js不能解构

    你可以:

    a- 以这种方式设置它们的默认值:

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

    b- 通过使用&lt;messages {...currentUser}&gt; 解构上游对象并使用messages.defaultProps = { credentials: { username: 'foo', image: 'bar' }} 或在定义组件的位置添加defaultProps 类属性来设置它们的默认值,将每个currentUser 属性作为道具传递。这可以被视为更惯用的方式

    c- 使用组件时确保credentials 永远不是undefined ^^

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 1970-01-01
      • 2021-03-08
      • 2021-05-11
      • 2021-04-04
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多