ReduxToolkit解决redux不能使用class创建对象

因为开发了个sdk插件需要一个全局管理,第一想的的是Redux去管理,但是使用new 创建的对象类无法使用且会报错,后续找到了解决方案;

报错:A non-serializable value was detected in the state

原因:一般来说,React 和 Redux 应用程序应该使用纯 JS 对象和数组作为数据来编写,要使用"模型类class{}"

项目中版本
"@reduxjs/toolkit": "^1.9.1",
"react-redux": "^8.0.5",
解决方案代码
middleware: getDefaultMiddleware =>
    getDefaultMiddleware({
      serializableCheck: false,
}),
实际使用
import { configureStore } from '@reduxjs/toolkit'
import { userSlice } from './slices/user';
//configureStore挂载每一个modules
const store = configureStore({
    reducer: {
      user: userSlice.reducer, //user module
    },
    // devTools: true,
    middleware: getDefaultMiddleware =>
      getDefaultMiddleware({
      serializableCheck: false,
    }),
});

//定义 ts types
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

export default store;
  • 27
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React-Redux是一个React状态管理库,它将Redux集成到React中,使得在React应用中使用Redux更加容易。要使用React-Redux,需要创建一个Redux store并将其提供给React应用。 创建仓库的步骤如下: 1. 安装ReduxReact-Redux: ``` npm install redux react-redux ``` 2. 创建store: ``` import { createStore } from 'redux'; import rootReducer from './reducers'; const store = createStore(rootReducer); ``` rootReducer是一个将多个reducer组合在一起的函数。 3. 将store提供给应用: ``` import { Provider } from 'react-redux'; import App from './App'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); ``` Provider是一个React组件,它将store作为props传递给应用中的所有组件。 使用React-Redux来管理状态的步骤如下: 1. 连接组件: ``` import { connect } from 'react-redux'; function mapStateToProps(state) { return { user: state.user }; } function mapDispatchToProps(dispatch) { return { updateUser: (user) => dispatch({ type: 'UPDATE_USER', payload: user }) }; } export default connect(mapStateToProps, mapDispatchToProps)(MyComponent); ``` connect是一个高阶函数,它将组件连接到store。mapStateToProps和mapDispatchToProps是两个函数,它们将store中的状态和dispatch方法映射到组件的props中。 2. 在组件中使用状态: ``` function MyComponent(props) { return ( <div> <h1>{props.user.name}</h1> </div> ); } ``` 在组件中可以通过props来获取状态。 3. 在组件中更新状态: ``` function MyComponent(props) { function handleClick() { props.updateUser({ name: 'New Name' }); } return ( <div> <h1>{props.user.name}</h1> <button onClick={handleClick}>Update Name</button> </div> ); } ``` 在组件中可以通过props来调用dispatch方法来更新状态。这里更新了user的name属性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值