【问题标题】:How to access properties added by mapStateToProps in mapDispatchToProps?如何访问 mapDispatchToProps 中 mapStateToProps 添加的属性?
【发布时间】:2018-10-28 08:11:37
【问题描述】:

React Redux 提供函数 connect 将 Redux statedispatch 绑定到 React 组件(作为属性)。

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

mapStateToProps(state, [ownProps]): stateProps

mapDispatchToProps(dispatch, [ownProps]): dispatchProps

如何访问函数mapStateToProps在函数mapDispatchToProps中添加的属性?

比如我使用函数mapStateToProps给组件添加属性propertyFromState,如何在函数mapDispatchToProps中访问属性propertyFromState

我尝试使用参数ownProps来访问它,但它是undefined

【问题讨论】:

    标签: javascript reactjs redux react-redux jsx


    【解决方案1】:

    在mapDispatchToProps中无法访问状态,这很荒谬。 还有一个redux的替代品,Dynadux,简单又解决了redux的繁琐。

    【讨论】:

      【解决方案2】:

      有用的链接:What is mapDispatchToProps?

      mapStateToProps() 用于从 Redux/应用程序状态访问变量

      function mapStateToProps(state) {
      return {
          token: reduxState.token
      };
      }
      

      可以在 React Component 中使用 this.props.token 访问它。

      并且 mapDispatchToProps 触发一个动作事件(调度一个可能导致应用程序状态改变的动作)

      const mapDispatchToProps = (dispatch) =>  {
      return{
          send:(variable) =>{dispatch(send(variable))}
      }
      }
      

      【讨论】:

        【解决方案3】:

        您无法访问 mapDispatchToProps 中的道具。相反,您可以在调用函数时将参数传递给函数。例如,如果你想将 prop 传递给 action,你可以通过多种方式做到这一点。

        第一:

        function mapDispatchToProps(dispatch) {
          return {
            onNameChanged: (name) => dispatch({ type: 'NAME_CHANGED', payload: name })
          }
        }
        

        或者

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

        从您的组件中调用 this.props.actions(propertyFromState)。在actions.js中创建动作以接受这样的参数

        function action1(property){
          return { type: 'NAME_CHANGED', payload: property }
        }
        

        【讨论】:

        • 也许这不是正确的方法。 Chrome 的控制台抛出大量错误:Warning: Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
        • 看起来您正在渲染方法中进行操作调用。您可以在此处粘贴您的代码 sn-p 以获得更好的解决方案吗?
        猜你喜欢
        • 1970-01-01
        • 2021-01-05
        • 1970-01-01
        • 2019-10-03
        • 2019-03-01
        • 2018-10-04
        • 2018-06-15
        • 1970-01-01
        • 2017-05-03
        相关资源
        最近更新 更多