首页 > 解决方案 > 失败的道具类型:道具`auth`在`Navbar`中标记为必填,但其值为`undefined`

问题描述

我在名为 NavBar.js 的功能组件中使用 useSelector 而不是 mapStateToProps 函数。当我运行程序时,我在控制台中看到了这个错误:

“失败的道具类型:道具auth被标记为必填Navbar,但它的值为undefined。”

我该如何解决?

import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect, shallowEqual, useSelector } from 'react-redux';
import { logoutUser } from '../../actions/authActions';
import { clearCurrentProfile } from '../../actions/profileActions';

 const Navbar = (props) => {

 const selectedData = useSelector((state) => state, shallowEqual)
 const { isAuthenticated, user } = selectedData.auth;

 return(
   //Code......
 )

}

Navbar.propTypes = {
logoutUser: PropTypes.func.isRequired,
clearCurrentProfile: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};


export default  withRouter(connect(null, { logoutUser, clearCurrentProfile })(Navbar));

标签: javascriptreactjsreduxfrontendreact-proptypes

解决方案


问题是您不再将状态映射到道具,但您的组件仍在期待道具。要解决此问题,您需要authpropTypes.

Navbar.propTypes = {
  logoutUser: PropTypes.func.isRequired,
  clearCurrentProfile: PropTypes.func.isRequired,
  auth: PropTypes.object.isRequired // this is the problem
};

我看到的另一个不相关的问题是您正在使用connect将动作创建者映射到道具。我建议通过使用来调度您的操作来connect完全删除使用。学到更多useDispatch()


推荐阅读