I'm connecting store to my react application, But it gives me error TypeError: state is undefined
store/index.js(Creating Reducer function)
import {createStore} from 'redux';
const counterReducer = (state:{counter:0},action) => {
if(action.type==='increment')
{
return {
counter: state.counter + 1
}
}
if (action.type === 'decrement') {
return {
counter: state.counter - 1
}
}
return state;
}
const store = createStore(counterReducer);
export default store;
main index.js(Main index of my file)
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import store from './store/index';
import './index.css';
import App from './App';
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
Now I'm using my Counter components like this:(src/components/Counter.js)
import classes from './Counter.module.css';
import {useSelector} from 'react-redux';
const Counter = () => {
const counter = useSelector(state => state.counter);
const toggleCounterHandler = () => {};
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
<div className={classes.value}>{counter}</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
</main>
);
};
export default Counter;
here is my package.json:
{
"name": "redux-basics",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.5",
"@testing-library/user-event": "^12.6.3",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-redux": "^7.2.4",
"react-scripts": "4.0.2",
"redux": "^4.1.0",
"web-vitals": "^1.1.0"
},
"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"
]
}
}
Error :
TypeError: state is undefined
Counter/counter<
C:/Users/nikku/Desktop/redux-project/src/components/Counter.js:6
3 |
4 |
5 | const Counter = () => {
> 6 | const counter = useSelector((state) => state.counter);
7 | const toggleCounterHandler = () => {};
8 |
9 | return (
useSelector should get state as argument by default right? but here it is saying it is undefined. Ca you please share you thoughts? Did I do something wrong ?
为了初始化默认状态,您需要使用=
赋值运算符
const counterReducer = (state = {counter:0},action) => {
Default state is initialized like this. This will fix your issue.
function appReducer(state = MyInitialState, action) {
switch (action.type) {
case "my_custom_type":
return {
...state
};
default:
return state;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.