【问题标题】:Redux-form ownProperties is undefinedRedux-form ownProperties 未定义
【发布时间】:2017-12-14 13:27:13
【问题描述】:

我有一个 redux-form 连接到状态如下:

export default connect(mapStateToProps)(reduxForm({
  form: 'MyForm',
  validate // validation function given to redux-form
})(MyForm));

我现在想获得一个 slug 值,它是一个 react-router 参数(在导航到这样的页面之后: browserHistory.push(`/mypage/${slug}`))。然而 ownProps 是空的:

const mapStateToProps = (state, ownProps) => {

    console.dir(ownProps); // ISSUE:  this is empty 

    const someField = selector(state, 'someField');
    ...
};

我尝试了不同的方式连接到 redux-form,但都没有成功。非常感谢有关如何解决此问题的任何提示。

【问题讨论】:

    标签: reactjs react-router redux-form url-parameters


    【解决方案1】:

    我想我已经理解了你的问题。您需要连接 redux 表单才能使用选择器获取值。请参阅下面的示例代码。希望对你有帮助。

    import React from 'react'
    import { Field, reduxForm, formValueSelector } from 'redux-form'
    import validate from './validate'
    import example from './components/example'
    
    import { connect } from 'react-redux'
    
    function myForm ({
      someProp,
      exampleClick
    }) {
      function handleSubmit (e) {
      }
      return <form onSubmit={handleSubmit}>
        <Field
          name='name'
          component={example}
          submitBtnClicked={exampleClick} />
      </form>
    }
    
    let thisForm = reduxForm({
      form: 'myForm',
      validate
    })(myForm)
    
    const selector = formValueSelector('myForm')
    
    thisForm = connect(
      state => {
        const someField = selector(state, 'someField')
        return ({someField})
      }
    )(thisForm)
    
    export default thisForm
    

    【讨论】:

    • 您好,Umesh,感谢您的回复。我已经有一个与您在此处发布的非常相似的实现。我的问题是不能让它与选择器一起工作。我的问题是我需要使用 ownProps 参数作为 mapStateToProps 的参数来从 url 中提取反应路由器参数。如果我添加它,ownProps 似乎总是未定义。我有一个不使用 redux-form 的组件,所以我的猜测是我没有正确使用 redux-form,或者 redux-form 不支持它。
    【解决方案2】:

    我通过在我连接的组件周围添加 react-router 的 withRouter 解决了这个问题:

    export default withRouter(connect(mapStateToProps)(reduxForm({
      form: 'MyForm',
      validate // validation function given to redux-form
    })(MyForm)));
    

    【讨论】:

      猜你喜欢
      • 2017-06-10
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 2015-02-27
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多