Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux not connecting to React component

I have been playing around with Redux, but I can't seem to get it to connect with React. I am using connect with mapStateToProps but the props in my store are not being passed into my component. Perhaps somebody could shed some light on why my code won't work? I'm guessing it has something to do with the mapStateToProps function.

Here's the code that I've got:

import { connect, Provider } from 'react-redux';
import { createStore, combineReducers } from 'redux';
import React from 'react';
import ReactDOM from 'react-dom';`enter code here`


const greetReducer = ( state = '', action ) => {

  if ( action.type === 'greet' ) {

  state = action.greeting

  }

  return state;

};

const runReducer = ( state = '', action ) => {

  if ( action.type === 'run' ) {

    state = action.running

  }

  return state;

};

const reducers = combineReducers({

  greetState: greetReducer,
  runState: runReducer

});

const store = createStore( reducers );

store.dispatch({

  type: 'greet',
  greeting: 'Hello'

});

console.log(store.getState());

store.dispatch({

  type: 'run',
  running: 'Running like the wind'

});

const App = (props) => <h1>{props.greeting}</h1>;

const mapStateToProps = function(store) {
  return {
    greeting: store.getState().greetState
  };
}

connect(mapStateToProps)(App);

ReactDOM.render(
  <Provider store={store}><App /></Provider>,
  document.getElementById('root')
);
like image 696
Happy Koala Avatar asked Mar 09 '26 23:03

Happy Koala


1 Answers

The connect function (or, rather, the function returned by connect) does not modify your component; it returns a new component, which you need to save to a variable:

const ConnectedApp = connect(mapStateToProps)(App);

ReactDOM.render(
  <Provider store={store}><ConnectedApp /></Provider>,
  document.getElementById('root')
);
like image 115
Jordan Running Avatar answered Mar 11 '26 13:03

Jordan Running



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!