无法从React组件中的道具读取属性

萨尔瓦

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.logcurrentChatChatRoom,它正确地显示在聊天。

currentChat:

     messages: []
     user1: {
        _id: "5d1328a91e0e5320706cdabb", 
        name: "sarvar", 
     }
     user2: {
        _id: "5d131405ce36ce0ebcf76ae1", 
        name: "jalol makhmudov"
      }
     __v: 0
     _id: "5d329aea3f34fe0b8c6cf336"

如果我渲染currentChat._id(请参阅中的<h3>元素ChatRoom),则会正确显示它。

但是如果我渲染currentChat.user1.namecurrentChat.user2.name(请参阅中的<h2>元素ChatRoom),则会出现错误

TypeError: Cannot read property 'name' of undefined
ron4ex

用更精确的形状初始化状态。

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.user1undefinedcurrentChat.user1.name将引发错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React组件中的“无法读取未定义的属性'onClick'”

类型错误:无法读取 React 组件中的 null 属性

const组件即使是道具也无法读取undefined属性?

尝试在 React 中的功能组件内使用道具时,我收到 TypeError:无法设置未定义的属性“道具”?

未捕获的类型错误:无法读取 react-redux 中未定义的属性“道具”

在react中传递函数作为道具,无法读取未定义的属性“ edit”

在子组件中无法读取包含对象数组的道具

`TypeError:无法读取功能组件中React中未定义的属性'map'

无法读取表单中未定义的属性“道具”

反应原生组件无法访问道具 - TypeError:无法读取未定义的属性“导航”

如何在此React组件中修复“无法分配为仅读取对象的属性'样式'”?

使用NativeBase Toast组件时无法在React Native中读取null的'_root'属性

TypeError:无法读取未定义的属性“ 49”;用于React中的MachineTyping效果组件

React无法读取组件上未定义的属性“ map”

无法在React中读取null的属性'style'

无法读取 React js 中的属性

Vue组件无法读取属性

React组件中的儿童道具

无法读取功能组件中未定义的属性“ props”

Angular无法读取组件/表单中未定义的属性

错误:无法在 ReactJS 中读取未定义的属性(读取“道具”)

无法在 React 中读取未定义的属性(读取“地图”)

React TypeError:无法通过传递的道具读取未定义的属性“ map”

如何解决 React 和 Redux 抛出无法读取未定义错误的属性“道具”?

无法使用我的道具读取React上未定义的属性“名称”

React - 单击按钮时无法读取未定义的属性“道具”

类型错误:无法读取未定义的 React Hooks 道具问题的属性“标题”和地图

在React中更改高阶组件中的道具

无法从子组件中获取道具