我正在使用这样的路线:
import React from 'react';
import { useParams } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import AdminBank from 'views/Bank/Bank';
import CustomerBank from 'views/CustomerBank/CustomerBank';
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators({}, dispatch),
});
const BankContainer = (props) => {
const { userType } = useParams();
return (
userType === "admin" ? <AdminBank/> : <CustomerBank/>
)
}
export default connect(
BankContainer,
mapDispatchToProps
)(BankContainer);
Bank组件是redux容器组件。在内部,我有一个基于用户类型的条件渲染。
const BankContainer = (props) => {
const { userType } = useParams();
return (
userType === "admin" ? <Bank/> : <CustomerBank/>
)
}
我收到反应警告,然后出现反应错误
警告:
Warning: React has detected a change in the order of Hooks called by ConnectFunction. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks
Previous render Next render
------------------------------------------------------
1. useMemo useMemo
2. useMemo useMemo
3. useContext useContext
4. useMemo useMemo
5. useMemo useMemo
6. useMemo useMemo
7. useReducer useReducer
8. useRef useRef
9. useRef useRef
10. useRef useRef
11. useRef useRef
12. useMemo useMemo
13. useContext useLayoutEffect
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
in ConnectFunction (at Admin.js:68)
in Route (at Admin.js:68)
in Switch (at Admin.js:63)
in div (at Admin.js:59)
in Admin (created by ConnectFunction)
in ConnectFunction (at ProtectedRoute.js:13)
in Route (at ProtectedRoute.js:29)
in ProtectedRoute (at ProtectedRoute.js:46)
in ProtectedAdminRoute (created by ConnectFunction)
in ConnectFunction (at Main.js:46)
in Switch (at Main.js:45)
in Router (created by BrowserRouter)
in BrowserRouter (at Main.js:44)
in Main (created by ConnectFunction)
in ConnectFunction (at src/index.js:63)
in App (at src/index.js:69)
in Provider (at src/index.js:68)
错误:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
我的package.json版本:
"react-redux": "^7.2.0",
"react-router-dom": "5.2.0",
"react": "16.13.1",
"react-dom": "16.13.1",
我尝试过的事情:
答案 0 :(得分:1)
您要将BankContainer
传递给connect函数的mapStateToProps
参数,这肯定是错误的。你应该别的东西...
答案 1 :(得分:1)
嗨,@ ThatAnnoyingDude在第一个回答中说,这个正确的react-redux connect得到2个参数,它们是 mapStateToProps-带您从redux作为道具返回请求的状态 mapDispatchToProps-将您带回作为道具的redux请求的动作 如果您不想通过其中之一,则应该这样做:
export default connect(
null,
mapDispatchToProps
)(BankContainer);
第二个工作相同。