繁体   English   中英

理解 React-Redux 和 mapStateToProps()

[英]Understanding React-Redux and mapStateToProps()

我试图了解 react-redux 的 connect 方法,以及它作为参数的函数。 特别是mapStateToProps()

按照我的理解, mapStateToProps的返回值将是一个从状态派生的对象(因为它存在于商店中),其键将作为道具传递给您的目标组件(应用了组件连接)。

这意味着您的目标组件使用的状态可能与存储在您的商店中的状态具有截然不同的结构。

问:这样好吗?
问:这是预期的吗?
问:这是一种反模式吗?

是的,它是正确的。 它只是一个帮助函数,可以更简单地访问您的状态属性

想象一下,您的 App state.posts有一个posts

state.posts //
/*    
{
  currentPostId: "",
  isFetching: false,
  allPosts: {}
}
*/

和组件Posts

默认情况下connect()(Posts)将使所有状态道具可用于连接的组件

const Posts = ({posts}) => (
  <div>
    {/* access posts.isFetching, access posts.allPosts */}
  </div> 
)

现在,当您将state.posts映射到您的组件时,它会变得更好一些

const Posts = ({isFetching, allPosts}) => (
  <div>
    {/* access isFetching, allPosts directly */}
  </div> 
)

connect(
  state => state.posts
)(Posts)

mapDispatchToProps

通常你必须写dispatch(anActionCreator())

使用bindActionCreators你也可以更轻松地做到这一点

connect(
  state => state.posts,
  dispatch => bindActionCreators({fetchPosts, deletePost}, dispatch)
)(Posts)

现在你可以在你的组件中使用它

const Posts = ({isFetching, allPosts, fetchPosts, deletePost }) => (
  <div>
    <button onClick={() => fetchPosts()} />Fetch posts</button>
    {/* access isFetching, allPosts directly */}
  </div> 
)

actionCreators 更新..

actionCreator 的一个例子: deletePost

const deletePostAction = (id) => ({
  action: 'DELETE_POST',
  payload: { id },
})

因此, bindActionCreators只会执行您的操作,将它们包装到dispatch调用中。 (我没有阅读 redux 的源代码,但实现可能是这样的:

const bindActionCreators = (actions, dispatch) => {
  return Object.keys(actions).reduce(actionsMap, actionNameInProps => {
    actionsMap[actionNameInProps] = (...args) => dispatch(actions[actionNameInProps].call(null, ...args))
    return actionsMap;
  }, {})
}

问: Is this ok?
答:是的

问: Is this expected?
是的,这是预期的(如果您使用的是 react-redux)。

问: Is this an anti-pattern?
A:不,这不是反模式。

这称为“连接”您的组件或“使其变得智能”。 这是设计使然。

它允许您将组件与状态分离额外的时间,从而增加代码的模块化。 它还允许您将组件状态简化为应用程序状态的子集,这实际上有助于您遵守 Redux 模式。

可以这样想:商店应该包含应用程序的整个状态。
对于大型应用程序,这可能包含嵌套许多层的数十个属性。
您不想在每次通话时都拖着所有这些(昂贵)。

如果没有mapStateToProps或类似的东西,你会很想用另一种方式来mapStateToProps你的状态来提高性能/简化。

你做对了第一部分:

是的mapStateToProps将 Store 状态作为参数/参数(由react-redux::connect ),并用于将组件与 store 状态的某些部分链接起来。

通过链接,我的意思是mapStateToProps返回的对象将在构建时作为道具提供,任何后续更改都可以通过componentWillReceiveProps

如果你知道观察者设计模式,它就是它的那个或它的小变化。

一个例子将有助于使事情更清楚:

import React, {
    Component,
} from 'react-native';

class ItemsContainer extends Component {
    constructor(props) {
        super(props);

        this.state = {
            items: props.items, //provided by connect@mapStateToProps
            filteredItems: this.filterItems(props.items, props.filters),
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            filteredItems: this.filterItems(this.state.items, nextProps.filters),
        });
    }

    filterItems = (items, filters) => { /* return filtered list */ }

    render() {
        return (
            <View>
                // display the filtered items
            </View>
        );
    }
}

module.exports = connect(
    //mapStateToProps,
    (state) => ({
        items: state.App.Items.List,
        filters: state.App.Items.Filters,
        //the State.App & state.App.Items.List/Filters are reducers used as an example.
    })
    // mapDispatchToProps,  that's another subject
)(ItemsContainer);

可以有另一个名为itemsFilters组件来处理显示并将过滤器状态持久化到 Redux Store 状态,Demo 组件正在“侦听”或“订阅”Redux Store 状态过滤器,因此每当过滤器存储状态发生变化时(在filtersComponent的帮助下) ) react-redux 检测到有更改并通过将更改发送到它们的componentWillReceiveProps来通知或“发布”所有侦听/订阅组件状态发生了变化。

让我知道该示例是否令人困惑或不够清楚以提供更好的解释。

至于:这意味着您的目标组件使用的状态可能与存储在您的商店中的状态具有截然不同的结构。

我没有得到问题,但只知道反应状态( this.setState )与 Redux Store 状态完全不同!

react 状态用于处理 react 组件的重绘和行为。 反应状态仅包含在组件中。

Redux Store 状态是 Redux reducers 状态的组合,每个状态负责管理一小部分应用程序逻辑。 任何组件都可以在react-redux::connect@mapStateToProps的帮助下访问这些 reducers 属性! 这使得 Redux 存储状态可在应用程序范围内访问,而组件状态是其自身独有的。

这个react & redux示例基于 Mohamed Mellouki 的示例。 但使用美化linting 规则进行验证。 请注意,我们使用PropTypes定义了我们的 props 和dispatch方法,以便我们的编译器不会对我们尖叫。 这个例子还包括一些在 Mohamed 的例子中缺失的代码行。 要使用 connect,您需要从react-redux导入它。 此示例还绑定了 filterItems 方法,这将防止组件中的范围问题。 此源代码已使用 JavaScript Prettify自动格式化。

import React, { Component } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

class ItemsContainer extends Component {
  constructor(props) {
    super(props);
    const { items, filters } = props;
    this.state = {
      items,
      filteredItems: filterItems(items, filters),
    };
    this.filterItems = this.filterItems.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    const { itmes } = this.state;
    const { filters } = nextProps;
    this.setState({ filteredItems: filterItems(items, filters) });
  }

  filterItems = (items, filters) => {
    /* return filtered list */
  };

  render() {
    return <View>/*display the filtered items */</View>;
  }
}

/*
define dispatch methods in propTypes so that they are validated.
*/
ItemsContainer.propTypes = {
  items: PropTypes.array.isRequired,
  filters: PropTypes.array.isRequired,
  onMyAction: PropTypes.func.isRequired,
};

/*
map state to props
*/
const mapStateToProps = state => ({
  items: state.App.Items.List,
  filters: state.App.Items.Filters,
});

/*
connect dispatch to props so that you can call the methods from the active props scope.
The defined method `onMyAction` can be called in the scope of the componets props.
*/
const mapDispatchToProps = dispatch => ({
  onMyAction: value => {
    dispatch(() => console.log(`${value}`));
  },
});

/* clean way of setting up the connect. */
export default connect(mapStateToProps, mapDispatchToProps)(ItemsContainer);

此示例代码是一个很好的模板,可作为组件的起点。

React-Redux connect用于为每个操作更新存储。

import { connect } from 'react-redux';

const AppContainer = connect(  
  mapStateToProps,
  mapDispatchToProps
)(App);

export default AppContainer;

在这个博客中非常简单明了地解释了。

您可以克隆 github 项目或复制粘贴该博客中的代码以了解 Redux 连接。

这是一个简单的概念。 Redux 从 reducer 中的操作创建一个无处不在的状态对象(一个存储)。 像 React 组件一样,这种状态不必在任何地方显式编码,但它可以帮助开发人员在 reducer 文件中查看默认状态对象,以可视化正在发生的事情。 您在组件中导入 reducer 以访问该文件。 然后 mapStateToProps 仅选择其组件需要的存储中的键/值对。 把它想象成 Redux 创建一个 React 组件的全局版本

this.state = ({ 
cats = [], 
dogs = []
})

使用 mapStateToProps() 改变状态的结构是不可能的。 您正在做的是仅选择组件需要的商店键/值对,并将值(来自商店中的键/值列表)传递给组件中的道具(本地键)。 在列表中一次执行一个值。 在此过程中不会发生结构变化。

PS商店是本地状态。 Reducers 通常也会将状态传递给数据库,Action Creators 也参与其中,但首先要了解这个简单的概念,以了解这个特定的帖子。

PPS 将reducer 分成单独的文件并只导入组件需要的reducer 是一种很好的做法。

这是用于描述mapStateToProps行为的大纲/样板:

(这是 Redux 容器功能的极大简化实现。)

class MyComponentContainer extends Component {
  mapStateToProps(state) {
    // this function is specific to this particular container
    return state.foo.bar;
  }

  render() {
    // This is how you get the current state from Redux,
    // and would be identical, no mater what mapStateToProps does
    const { state } = this.context.store.getState();

    const props = this.mapStateToProps(state);

    return <MyComponent {...this.props} {...props} />;
  }
}

接下来

function buildReduxContainer(ChildComponentClass, mapStateToProps) {
  return class Container extends Component {
    render() {
      const { state } = this.context.store.getState();

      const props = mapStateToProps(state);

      return <ChildComponentClass {...this.props} {...props} />;
    }
  }
}

是的,你可以这样做。 您甚至可以处理状态并返回对象。

function mapStateToProps(state){  
  let completed = someFunction (state);
   return {
     completed : completed,  
   }
}
 

如果您想将与状态相关的逻辑从渲染函数转移到它的外部,这将非常有用。

我想重新构建您提到的声明,即:

这意味着您的目标组件使用的状态可能与存储在您的商店中的状态具有截然不同的结构

您可以说目标组件消耗的状态有一小部分状态存储在 redux 存储中。 换句话说,您的组件消耗的状态将是 redux 存储状态的子集。

就理解 connect() 方法而言,它相当简单! connect() 方法有能力向你的组件添加新的 props,甚至覆盖现有的 props。 正是通过这个 connect 方法,我们也可以访问由提供者抛出给我们的 redux 存储的状态。 两者的组合对您有利,您可以将 redux 存储的状态添加到组件的 props 中。

以上是一些理论,我建议您看一次此视频以更好地理解语法。

import React from 'react';
import {connect} from 'react-redux';
import Userlist from './Userlist';

class Userdetails extends React.Component{

render(){
    return(
        <div>
            <p>Name : <span>{this.props.user.name}</span></p>
            <p>ID : <span>{this.props.user.id}</span></p>
            <p>Working : <span>{this.props.user.Working}</span></p>
            <p>Age : <span>{this.props.user.age}</span></p>
        </div>
    );
 }

}

 function mapStateToProps(state){  
  return {
    user:state.activeUser  
}

}

  export default connect(mapStateToProps, null)(Userdetails);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM