简体   繁体   English

Redux如何将状态传递给mapStateToProps?

[英]How is Redux passing state to mapStateToProps?

I'm trying to understand how React and Redux work, and I was looking at FuelSavingsPage.js from this example project . 我正在尝试理解React和Redux是如何工作的,而我正在查看此示例项目中的 FuelSavingsPage.js。 I get where actions comes from in mapDispatchToProps , but I don't understand how state is being passed to mapStateToProps or how dispatch is being passed to mapDispatchToProps . 我得到mapDispatchToProps中的actions来源,但我不明白如何将state传递给mapStateToProps或如何dispatch传递给mapDispatchToProps How is this happening? 这是怎么回事?

import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../actions/fuelSavingsActions';
import FuelSavingsForm from '../components/FuelSavingsForm';

export const FuelSavingsPage = (props) => {
  return (
    <FuelSavingsForm
      saveFuelSavings={props.actions.saveFuelSavings}
      calculateFuelSavings={props.actions.calculateFuelSavings}
      fuelSavings={props.fuelSavings}
    />
  );
};

FuelSavingsPage.propTypes = {
  actions: PropTypes.object.isRequired,
  fuelSavings: PropTypes.object.isRequired
};

function mapStateToProps(state) {
  return {
    fuelSavings: state.fuelSavings
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(actions, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(FuelSavingsPage);

All magic in connect() function. connect()函数中的所有魔法。 This function calls mapStateToProps and passes state as a prop. 此函数调用mapStateToProps并将state作为prop传递。 The same thing happens with mapDispatchToProps and the dispatch method. mapDispatchToPropsdispatch方法mapDispatchToProps发生同样的事情。 You can imagine this with the following pseudo-code: 您可以使用以下伪代码来设想:

function connect(mapStateToProps, mapDispatchToProps) {
    mapStateToProps(store.getState()) // just simple callback
    mapDispatchToProps(store.dispatch) // the same
}

The React-Redux connect function generates a wrapper component that subscribes to the store. React-Redux connect函数生成一个订阅商店的包装器组件。 That wrapper component calls store.getState() after each dispatched action, calls the supplied mapStateToProps function with the current store state, and if necessary, calls mapDispatchToProps with the store's dispatch function. 该包装器组件在每次调度操作后调用store.getState() ,使用当前存储状态调用提供的mapStateToProps函数,并在必要时使用存储的dispatch函数调用mapDispatchToProps

Dan wrote a simplified version of connect a while back to illustrate the general approach it uses. Dan写了一段简化版本的connect ,以说明它使用的一般方法。 See https://gist.github.com/gaearon/1d19088790e70ac32ea636c025ba424e . 请参阅https://gist.github.com/gaearon/1d19088790e70ac32ea636c025ba424e

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

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