DeLe
DeLe

Reputation: 2480

How to use state in component through connect

I am using reactjs and redux to build my simple app. I follow some tutorial and i get an error.

My connect

const mapStateToProps = function(state) {
     console.log(state) // WHAT IS FORMAT? {....}
     return {
          messages: state.messages // i don't know state contain messsages key
     }
}

export default connect(mapStateToProps)(MyComponent);

and MyComponent

const MyComponent= ({messages}) => (
        <ul>
            {messages.map(message => (
                <Child
                    key={message.id}
                    {...message}
                />
            ))}
        </ul>
)

I create my store by

createStore(
        reducer, applyMiddleware(myMiddleware())
    );

But i don't know state format. it is object of some key ? I don't find any define state format in tut, and i get an error

Uncaught TypeError: Cannot read property 'map' of undefined

How to understand and fix that.

Upvotes: 0

Views: 26

Answers (1)

Steven Laidlaw
Steven Laidlaw

Reputation: 450

The state parameter provided to connect is an object that contains the current redux state. Anything you’ve created using your reducers will be available here.

See https://redux.js.org/api/store#getState for more information.

In your case you likely haven’t set up any reducers yet, and so the messages store object isn’t yet populated. If you complete the tutorial it will take you through the setup.

Upvotes: 1

Related Questions