trying to figure out how to pull Redux store state into my component from Redux. I've got mapStateToProps and "connect" wired up. However, when I click my button in "App" component, this.props doesn't have my Redux values in it.
// React and Redux Const
const { Component } = React;
const { render } = ReactDOM;
const { Provider, connect } = ReactRedux;
const {createStore, combineReducers, bindActionCreators } = Redux;
function tweetReducer(state=[],action) {
if(action.type === 'ADD_TWEET') {
return state.concat({ id: Date.now(), tweet: action.payload})
} else {
return state;
}
}
const rootReducer = combineReducers ({
state: (state = {}) => state,
tweets: tweetReducer
});
class App extends Component{
buttonClicked() {
store.dispatch({type: 'ADD_TWEET', payload: 'This is my first
tweet!'});
console.log(this.props)
}
render() {
return (
<div>
<h5>Hello from App</h5>
<button onClick={this.buttonClicked.bind(this)}>Button</button>
<div>-------------------</div>
<Display />
</div>
)
}
}
class Display extends Component {
render() {
return (
<div>
<h3>Tweets:</h3>
{this.props.tweets}
</div>
)
}
}
function mapStateToProps(state) {
console.log('mapping state to props')
return {
tweets: state.tweets
}
}
let store = createStore(rootReducer)
render (
<Provider store={store}>
<App />
</Provider>
, document.querySelector('#app')
);
connect(mapStateToProps)(App)
console.log(store.getState());
Looks like you've got a couple issues there.
First, it helps to understand that
connect()(MyComponent)
returns a new component that "wraps" around your "real" component. In your example, you're callingconnect()
after you've rendered<App />
, and you aren't actually saving and using the component generated byconnect()
. What you need is something like:Second, part of the point of connecting a component is that it shouldn't actually reference the store directly.
connect()
can take a second parameter, known asmapDispatchToProps
. If you don't supply amapDispatch
parameter, it will automatically give your componentthis.props.dispatch
. So, your App component should look like this to start with:That should be enough to get the App component receiving data from Redux and dispatching actions.
This is how you should proceed with getting store state in your component.
1) Create reducers folder and create a new file index.js
/* reducers/tweetReducer.js */
/* components/App.js */
/* components/Display.js */
/*Main.js */
/* store/index.js */