如何使用 react-redux 的连接 [英] How to use connect from react-redux

查看:47
本文介绍了如何使用 react-redux 的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 connect() 时遇到了一点问题.我认为将所有组件包装在 Provider 中会起作用,但事实证明它不是......所以我发现我需要使用 react-redux 中的 connect().问题是我不知道我应该如何使用它.这个站点是展示了一些例子,但是,我没有任何动作创建者可以放入连接中,因为我不使用它们......有人可以给我一些建议吗?我只想访问我在组件内的商店...

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

推荐答案

为了在你的容器中使用你的商店,你需要做两件事

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

首先:利用 mapStateToProps() .顾名思义,它将状态变量从您的商店映射到您指定的道具

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

其次:您需要将这些 props 连接到您的容器.这就是 connect() 出现的地方.mapStateToProps 组件返回的对象连接到容器.您可以从 react-redux 导入连接,例如 import {connect} from 'react-redux';

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

示例

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

这篇关于如何使用 react-redux 的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆