React redux 存储未连接



我正在将存储连接到我的react应用程序,但它给了我错误类型错误:状态是未定义的

store/index.js(创建Reducer函数(

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(我的文件的主索引(

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'));

现在我使用的Counter组件如下:(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;

这是我的包.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"
]
}
}

错误

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默认情况下应该将state作为参数,对吗?但在这里,它说它是未定义的。你能分享一下你的想法吗?我做错什么了吗?

为了初始化默认状态,您需要使用=赋值运算符

const counterReducer = (state = {counter:0},action) => {

默认状态初始化如下。这将解决您的问题。

function appReducer(state = MyInitialState, action) {
switch (action.type) {
case "my_custom_type":
return {
...state
};
default:
return state;
}
}

相关内容

  • 没有找到相关文章

最新更新