用户名属性显示为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下的凭据下
答案 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