javascript - 失败的道具类型:道具`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));
解决方案
问题是您不再将状态映射到道具,但您的组件仍在期待道具。要解决此问题,您需要auth
从propTypes
.
Navbar.propTypes = {
logoutUser: PropTypes.func.isRequired,
clearCurrentProfile: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired // this is the problem
};
我看到的另一个不相关的问题是您正在使用connect
将动作创建者映射到道具。我建议通过使用来调度您的操作来connect
完全删除使用。学到更多useDispatch()
推荐阅读
- python - 由于 EnviromentError 无法安装软件包 - Python
- javascript - 过滤一个集合数据值一个承诺
- amazon-aurora - wal_level < 升级极光 postgres db 时出现逻辑错误
- python - 如何使用 `PyQt5` 后端使来自`matplotlib` 的控制台消息静音?
- flutter - 如何创建具有与其父类构造函数不同的参数的自定义(ElevatedButton)类构造函数?
- postgresql - 如何在 Postgres 中选择更新表 A 中的一行和表 B 中的所有连接行?
- javascript - Get and merge all the documents in MongoDB which were inserted in the last minute by using Node.js
- c++ - 在函数超出范围后保留特征矩阵不被删除
- deep-learning - 描述基于 LSTM 层/网络的工作负载时缺少特征大小
- java - 列出字符串中的字符