简体   繁体   中英

Redux store not being passed to props on component

Learning Redux and React, and I'm having an issue where I have the store created, and passed over to my <Provider> through react-redux, but I get an empty object when logging in the console.

import {  createStore,  applyMiddleware } from 'redux';
import  logger from 'redux-logger';
import  thunk from 'redux-thunk';

import uuid from 'uuid';


var defaultState = {
  tasks: [{
    key: uuid.v4(),
    name: 'learn Redux',
    description: 'Learn how to create a completely statefully managed application.',
    priority: 1,
    notes: [{
      key: uuid.v4(),
      content: 'Creation of the store is paramount. One must import {createStore, applyMiddleware from redux package}, then define the root reducer, and create the store with applymiddleware, and then export the store.'
    }],
  }, ]
};

var root = (state = defaultState, action) => {
  return state;
};

var store = createStore(root, applyMiddleware(thunk,logger));

export default store;

I think the issue may lie with how I'm passing it to the <Provider> component, but that also could be wrong. Just for good measure, here is my App component.

import React, { Component } from 'react';
import './App.css';
import store from './store/createStore';
import { Provider } from 'react-redux';


class App extends Component {
  render() {
    console.log(this.props);
    // let tasks = this.props.tasks.map(x => {
    //   return <p>{x.name}</p>
    // })
    return (
      <Provider store={store}>
        <h1>Nothing to see here.</h1>
      </Provider>
    );
  }
}

export default App;

<Provider> "provides" the store prop to components placed below it that use connect() .

You can't place the <Provider> within a component's render function and change the props passed to it. It's already too late at that point. The props are what they are.

That will happen above this component in the tree, either another component or during your ReactDOM.render call.

The redux state does not automatically show up as props everywhere; and rightfully so. If that is the case, the performance would be devastating unless you have custom shouldComponentUpdate .

What you need to use is connect the redux state to your component. For your example, it'll be something like:

import { connect } from 'react-redux';

...

// Replace last line with this:
export default connect(
  state => ({ tasks: state.tasks }),
  null,
)(App);

Now, this.props.tasks will be the tasks in your redux state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM