未捕获的类型错误:无法读取未定义的属性(读取“getState”)
2023-03-29
514
我正在尝试运行 react redux,但不幸的是我得到了未定义的错误。以下是错误显示:
Uncaught TypeError: Cannot read properties of undefined (reading 'getState')
错误似乎来自 index.js 文件,特别是 Provider store={store},但我可能是错的。
这是我使用的文件列表:
index.js
import App from './App';
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import store from './store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}> {/* This will make store accessible to the entire component tree */}
<App />
</Provider>
</React.StrictMode>
);
store.js
import { configureStore } from "@reduxjs/toolkit";
import pizzaReducer from './pizzaSlice';
const store = configureStore({
reducer: {
pizza: pizzaReducer,
}
})
export default store.reducer;
pizzaSlice.js
import { configureStore } from "@reduxjs/toolkit";
import pizzaReducer from './pizzaSlice';
const store = configureStore({
reducer: {
pizza: pizzaReducer,
}
})
export default store.reducer;
App.js
import { useDispatch, useSelector } from 'react-redux';
import { addTopping, toggleGluten } from './pizzaSlice';
import './App.css';
function App() {
const pizza = useSelector(state => state.pizza);
const dispatch = useDispatch(); // dispatch action
return (
<div className="App">
<h1>Pizza</h1>
{
pizza.toppings.map(toppings => (
<div key={toppings}>{toppings}</div>
))
}
<button onClick={dispatch(addTopping('ham'))}> Add Ham </button>
<button onClick={dispatch(addTopping('mushroom'))}> Add Mushroom </button>
<button onClick={dispatch(addTopping('pepperoni'))}> Add Pepperoni </button>
<button onClick={dispatch(toggleGluten())}> Toogle Gluten </button>
</div>
);
}
export default App;
package.json
{
"name": "react-redux-sample",
"version": "0.1.0",
"private": true,
"dependencies": {
"@reduxjs/toolkit": "^1.9.3",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^8.0.5",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
我尝试过使用 redux 中的 createStore,但它也不起作用
1个回答
您必须导出
store
而不是
store.reducer
import { configureStore } from "@reduxjs/toolkit";
import pizzaReducer from './pizzaSlice';
const store = configureStore({
reducer: {
pizza: pizzaReducer,
}
})
export default store;
Konrad
2023-03-29