Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use connect from react-redux [duplicate]

I'm having a little problem with connect(). I thought wrapping all components in Provider is going to work, but turns out it isn't.... So I found that I need to use connect() from react-redux. The problem is i don't know how should I use it. This site is showing some examples but, i don't have any action creators to put inside connect because I don't use them....... Can someone give me some advices? I just want to access my store inside components...

like image 738
Kreha Avatar asked Dec 07 '16 15:12

Kreha


2 Answers

In order to use your store in your container you need to do two things

Firstly : make use of mapStateToProps() . As the name suggests, it maps the state variables from your store to the props that you specify

Secondly : You need to connect these props to your container. This is where connect() comes into picture. The object returned by the mapStateToProps component is connected to the container. You can import connect from react-redux like import {connect} from 'react-redux';

Example

import React from 'react';
import { connect } from 'react-redux';

class App extends React.Component {
  render() {
    return <div>{this.props.containerData}</div>;
  }
}

function mapStateToProps(state) {
  return { containerData: state.appData };
}

export default connect(mapStateToProps)(App);
like image 102
Shubham Khatri Avatar answered Nov 18 '22 13:11

Shubham Khatri


You might have better luck with the Redux documentation here.

Here's a simple example of how the connect function works:

import React from 'react';
import { connect } from 'react-redux';

class Item extends React.Component {
  render() {
    return <div onClick={() => this.props.dispatch( /* some action here */ )}>{this.props.name}</div>;
  }
}

function mapStateToProps(state) {
  return { name: state.name };
}

export default connect(mapStateToProps)(Item);

What happens above is when you export the Item component, you're exporting the wrapped, connected component. Wrapping the component will pass in the prop name from the app state (it will also pass in the dispatch function as a prop.

like image 32
Ben Nyberg Avatar answered Nov 18 '22 13:11

Ben Nyberg