【发布时间】:2024-04-17 00:10:02
【问题描述】:
我正在使用这样的路线:
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",
我尝试过的方法:
- 已检查反应捆绑程序问题
- 切换到视图,而不仅仅是一个反应容器
- 试过其他的钩子,还是一样的问题
【问题讨论】:
-
不清楚
BankContainer的渲染位置?BankContainer和Bank一样吗? -
抱歉,Bank 和 BankContainer 是同一个组件。
-
你在任何地方都给
useLayoutEffect打电话吗? -
还有
Bank里面有redux 的Provider吗? -
这就是为什么我很困惑,我从来没有在这个项目的任何地方使用过这个钩子。只需使用效果。我知道 useContext 来自 react-router。不确定 useLayoutEffect 来自哪里。
标签: reactjs react-redux react-router-dom