简单的React Redux状态返回未定义

时间:2020-08-22 10:40:33

标签: reactjs redux react-redux store redux-reducers

我对此完全感到困惑。我构建了最简单的简单react redux组件,该组件目前仅显示商店中持有的计数器。但是,此计数器始终以未定义的形式返回!

我希望计数器返回0,因为这是化简器中的设置!

我已经关注了无数的教程,但是却无所适从!

//index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import counterReducer from './reducers/counterReducer';

const store = createStore(counterReducer);

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

//app.js

import React from 'react';
import { useSelector } from 'react-redux'; 


function App() {
  const counter = useSelector(state => state.counter)
  return (
    <div className="App">
      <p>{`counter is ${counter}`}</p>
    </div>
  );
}

export default App;

//actions.js

export const add = (nr) =>{
    return {
        type: 'ADD',
        payload:{
            nr
        }
    }
}

//counterReducer.js

const counterReducer = (state=0, action) => {
    switch(action.type){
        case "ADD":
            return state+1;
        default:
            return state;
    }
}

export default counterReducer;

如您所见,这是一个真正简单的设置。我希望计数器返回0,因为这是counterReducer.js

中设置的初始状态

但是我只是在前端看到“未定义计数器”!

1 个答案:

答案 0 :(得分:1)

从状态中删除.counter

// already a number
const counter = useSelector(state => state)

或将counter添加到您的redux根对象:

import {createStore, combineReducers } from 'redux';
import counterReducer from './reducers/counterReducer';

const store = createStore(combineReducers({counter: counterReducer});