How to use connect from react-redux [duplicate]

2020-07-13 08:20发布

问题:

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...

回答1:

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);


回答2:

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.