Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Reducer that simply returns an action's value and not a state?

I have a Container, an actionsCreator, and a reducer. In the below code, what's enabling the Reducer to return action.text instead of an updated state object? I thought reducers had to always return states.

HelloWorldContainer.jsx

 import { connect } from 'react-redux';
 import HelloWorld from '../components/HelloWorld';
 import * as actionCreators from '../actions/helloWorldActionCreators';

 const mapStateToProps = (state) => ({ name: state.name });

 export default connect(mapStateToProps, actionCreators)(HelloWorld);

helloWorldActionCreators.jsx

 import { HELLO_WORLD_NAME_UPDATE } from '../constants/helloWorldConstants';

 export const updateName = (text) => ({   
   type: HELLO_WORLD_NAME_UPDATE,  
   text, 
 });

helloWorldReducer.jsx

 import { combineReducers } from 'redux';
 import { HELLO_WORLD_NAME_UPDATE } from '../constants/helloWorldConstants';

 const name = (state = '', action) => {
   switch (action.type) {
     case HELLO_WORLD_NAME_UPDATE:
       return action.text
     default:
       return state;
   }
 };

 const mainReducer = combineReducers({ name });

 export default mainReducer;

(Code source: React on Rails).

like image 745
Matthew Hinea Avatar asked Nov 02 '25 00:11

Matthew Hinea


1 Answers

The name is just a slice of state. And action.text is the updated state.

After combineReducers({ name }), the state tree looks like:

{
  name: '..'
}

Besides, redux doesn't limit you that you can only use object as your state. If you pass name to createStore() directly without combineReducers, your entire state will become a plain string.

like image 51
CodinCat Avatar answered Nov 03 '25 16:11

CodinCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!