如何在 React 中使用 Redux 的 Provider [英] How to use Redux's Provider with React

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

问题描述

我一直在关注 ReduxJS 文档:与 React 一起使用

I've been following the ReduxJS documentation here: Usage with React

在文档的最后,它提到了提供者对象的使用,我将我的 App 组件包装在提供者中,如下所示:

At the end of the document it mentions usage of the provider object, I have wrapped my App component in the provider like so:

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import RootReducer from './app/reducers'
import App from './app/app'

const store = createStore(RootReducer)

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

然而,文档到此结束.如何在组件内取货提供者提供的商店?

However, that's where the documentation ends. How do I pickup the store provided by provider within the components?

推荐答案

通过组件访问商店的最佳方式是使用 connect() 函数,如文档中所述.这允许您将状态和动作创建者映射到您的组件,并在您的商店更新时自动传入它们.此外,默认情况下,它会将 dispatch 作为 this.props.dispatch 传入.这是文档中的一个示例:

The best way to access your store through a component is using the connect() function, as described in the documentation. This allows you to map state and action creators to your component, and have them passed in automatically as your store updates. Additionally, by default it will pass in dispatch as this.props.dispatch. Here's an example from the docs:

import { connect } from 'react-redux'
import { setVisibilityFilter } from '../actions'
import Link from '../components/Link'

const mapStateToProps = (state, ownProps) => {
  return {
    active: ownProps.filter === state.visibilityFilter
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onClick: () => {
      dispatch(setVisibilityFilter(ownProps.filter))
    }
  }
}

const FilterLink = connect(
  mapStateToProps,
  mapDispatchToProps
)(Link)

export default FilterLink

请注意,connect 实际上创建了一个新组件,该组件环绕您现有的组件!这种模式被称为 Higher-Order组件,并且通常是在 React 中扩展组件功能的首选方式(通过继承或混合之类的东西).

Note that connect actually creates a new component that wraps around your existing one! This pattern is called Higher-Order Components, and is generally the preferred way of extending a component's functionality in React (over stuff like inheritance or mixins).

由于它有相当多的性能优化并且通常不太可能导致错误,Redux 开发人员几乎总是建议使用 connect 而不是直接访问商店 - 但是,如果您有 非常需要较低级别访问权限的充分理由,Provider 组件使其所有子项都可以通过 this.context:

Due to it having quite a few performance optimizations and generally being less likely to cause bugs, the Redux devs almost always recommend using connect over accessing the store directly - however, if you have a very good reason to need lower level access, the Provider component makes it so all its children can access the store through this.context:

class MyComponent {
  someMethod() {
    doSomethingWith(this.context.store);
  }
}

这篇关于如何在 React 中使用 Redux 的 Provider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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