redux 上的数据存储 return 到初始状态

Data on redux store return to initial state

例如,我在应用程序启动时将 navigate 存储在 redux 存储中:

//in App.js file
import { useNavigate } from 'react-router-dom' 

const App = () => {
   const navigate = useNavigate();

   useEffect(() => {
      dispatch(addNavigate(navigate))
   }, [dispatch, navigate]); 
}

当我使用 useSelector select 在另一个组件的 redux store 中导航时,它 returns undefined。我该如何修复它(如果我不直接在此组件中使用 useNavigate)以及为什么导航对象变为初始状态?

来自 Redux 文档:

It is highly recommended that you only put plain serializable objects, arrays, and primitives into your store. It's technically possible to insert non-serializable items into the store, but doing so can break the ability to persist and rehydrate the contents of a store, as well as interfere with time-travel debugging.

If you are okay with things like persistence and time-travel debugging potentially not working as intended, then you are totally welcome to put non-serializable items into your Redux store. Ultimately, it's your application, and how you implement it is up to you. As with many other things about Redux, just be sure you understand what tradeoffs are involved.

综上所述,如果您仍想从 useNavigate 挂钩添加 navigate 函数,您将只能获得 navigate 的有效定义值,如果它从 react-router-dom.

BrowserRouter 的子组件中调用

所以在顶层组件中这是行不通的,相反我们需要为您的 App.js:

import { BrowserRouter } from 'react-router-dom'
import createStore from './createReduxStore'

const store = createStore()

const App = () => (
  <BrowserRouter>
    <Provider store={store}>
      <Content />
    </Provider
  </BrowserRouter>
)

然后在你的 Content 组件中你可以做你最初想要的:

import { useNavigate } from 'react-router-dom' 

const Content = () => {
   const navigate = useNavigate();

   useEffect(() => {
      dispatch(addNavigate(navigate))
   }, [navigate]); 
}