使用Redux Toolkit创建Store时出现Uncaught TypeError错误的原因?
问题描述
在使用Redux Toolkit创建Store时遇到错误:Uncaught TypeError: setting getter-only property "configureStore"
相关代码如下:src/store/index.js:
import { configureStore } from "@reduxjs/toolkit"; import uiSlice from "./ui-slice"; const store = configureStore = ({ reducer: { ui: uiSlice.reducer } }) export default store;
src/index.js:
import ReactDOM from 'react-dom/client'; import { Provider } from 'react'; import './index.css'; import App from './App'; import store from './store/index'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={store}> <App /> </Provider> );
错误原因与修复方案
错误1:Store创建语法错误
创建store时错误使用赋值运算符=,将导入的只读configureStore函数重新赋值,触发了只读属性修改的报错。正确写法是调用configureStore函数并传入配置对象。修正后的
src/store/index.js:import { configureStore } from "@reduxjs/toolkit"; import uiSlice from "./ui-slice"; const store = configureStore({ reducer: { ui: uiSlice.reducer } }) export default store;错误2:Provider组件导入路径错误
Provider是react-redux库提供的组件,你错误地从react中导入,会导致组件无法正确连接Redux Store。修正后的
src/index.js:import ReactDOM from 'react-dom/client'; import { Provider } from 'react-redux'; import './index.css'; import App from './App'; import store from './store/index'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={store}> <App /> </Provider> );
内容的提问来源于stack exchange,提问作者tukitooo1998
相关产品推荐
相关产品推荐

