在ChatRoom
组件中,我试图在2个用户之间加载聊天,以呈现聊天的用户名。要聊天,我正在关闭getCurrentChat
功能。
ChatRoom
零件
// importing everything
import { getCurrentChat } from '../../actions/chatActions';
class ChatRoom extends Component {
componentDidMount() {
// loading chat between 2 people
this.props.getCurrentChat(this.props.match.params.chatId);
};
render() {
const { loadingCurrentChat } = this.props.chat;
console.log(this.props.chat.currentChat);
return (
<div className="container">
{loadingCurrentChat ? <Spinner /> : (
<div className="row">
<h3>ChatId: {this.props.chat.currentChat._id}</h3>
<h2>Chat between {this.props.chat.currentChat.user1.name} и {this.props.chat.currentChat.user2.name}</h2>
</div>
)}
</div>
)
}
}
const mapStateToProps = (state) => ({
auth: state.auth,
chat: state.chat
});
export default connect(mapStateToProps, { getCurrentChat })(withRouter(ChatRoom));
chatActions.js
export const getCurrentChat = (chatId) => (dispatch) => {
dispatch(setLoadingCurrentChat());
axios.get(`/chat/${chatId}`)
.then(res =>
dispatch({
type: GET_CURRENT_CHAT,
payload: res.data
})
)
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err
})
);
};
chatReducer.js
// importing everything
const initialState = {
currentChat: {},
loadingCurrentChat: false,
};
export default function (state = initialState, action) {
switch (action.type) {
case SET_LOADING_CURRENT_CHAT:
return {
...state,
loadingCurrentChat: true
}
case GET_CURRENT_CHAT:
return {
...state,
currentChat: action.payload,
loadingCurrentChat: false
}
}
}
我处理来自chatActions.js
-的请求的服务器文件chatController.js
// requiring everything
exports.getCurrentChat = (req, res) => {
const chatId = req.params.chatId;
Chat.findById(chatId)
.populate('user1')
.populate('user2')
.exec()
.then(chat => res.json(chat))
.catch(err => res.status(400).json(err));
};
当我尝试console.log
了currentChat
中ChatRoom
,它正确地显示在聊天。
currentChat:
messages: []
user1: {
_id: "5d1328a91e0e5320706cdabb",
name: "sarvar",
}
user2: {
_id: "5d131405ce36ce0ebcf76ae1",
name: "jalol makhmudov"
}
__v: 0
_id: "5d329aea3f34fe0b8c6cf336"
如果我渲染currentChat._id
(请参阅中的<h3>
元素ChatRoom
),则会正确显示它。
但是如果我渲染currentChat.user1.name
和currentChat.user2.name
(请参阅中的<h2>
元素ChatRoom
),则会出现错误
TypeError: Cannot read property 'name' of undefined
用更精确的形状初始化状态。
const initialState = {
currentChat: {
user1: {}
},
loadingCurrentChat: false,
};
如果您无法执行此操作,请像currentChat.user1 && currentChat.user1.name
在JSX中进行访问之前进行检查。
getCurrentChat
是一个请求,这意味着需要花费一些时间来获取数据。React不会等待请求完成以进行渲染。我们定义的原因之一initialState
是因为在请求完成时,React用于initialState
渲染。
在您的情况下,initialState定义为
const initialState = {
currentChat: {},
loadingCurrentChat: false,
};
在JavaScript中,定义空对象时currentChat: {}
,可以访问其直接子级,而不会出现任何错误。因此currentChat._id
可访问但由于currentChat.user1
是undefined
,currentChat.user1.name
将引发错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句