我试图运行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条答案
按热度按时间dojqjjoe1#
必须导出
store
而不是store.reducer