How to use connect from react-redux [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-22 08:31:41

问题


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.



来源:https://stackoverflow.com/questions/41021369/how-to-use-connect-from-react-redux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!