如何访问另一个组件中的 redux 表单值

How to access redux form values in another component

我使用 Redux-Form 7.3.0。我试图在另一个组件中获取我的表单的值。我阅读了 Redux 表单 website 中的说明,但没有用。

this is the code of my componenet:

    import React from 'react'
    import { Field, reduxForm } from 'redux-form';
    import { connect } from 'react-redux';
    import { formValueSelector } from 'redux-form';

    class Test extends React.Component {
      render() {
        console.log(this.props);
        return (
          <div>
            test
            {this.props.title}      
          </div>
        );
      }
    }

    const selector = formValueSelector('NewPostForm');

    Test = connect(
      state => ({
        title: selector(state, 'title')
      })
    )(Test)

    export default Test;

这是我的表单组件:

从 'react' 导入 React; 从 'redux-form';

导入 { Field, reduxForm }
class NewPost extends React.Component {

    renderField(field) {          
        return (
            <div>
                <label>{field.label}</label>
                <input type="text"  {...field.input} />
            </div>
        );
    }

    showResults(values) {

        window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
    }

    render() {

        const { pristine, submitting, handleSubmit } = this.props;
        return (
            <form onSubmit={handleSubmit(this.showResults)} >
                <div>
                    <Field
                        label='Title'
                        name='title'
                        component={this.renderField}
                    />

                    <button type='submit' disabled={submitting}>
                        Submit the from :)
                    </button>                        
                </div>
            </form>
        );
    }
}



export default reduxForm({ form: 'NewPostForm'})(NewPost);

但我总是得到

title:undefined

我发现了同样的问题 但它对我没有帮助。

您的 Test 组件有两个来自 "redux-form" 的导入。请只做一个,像这样:

import { Field, reduxForm, formValueSelector } from 'redux-form'

如果您的 NewPost 组件在任何时候被卸载,可能是通过在导航期间更改视图或其他内容,窗体的状态就会被破坏。您可以通过将带有 false 值的 destroyOnUnmount 属性添加到您的 reduxForm 包装器来避免此类默认行为:

export default reduxForm({
   form: 'NewPostForm',
   destroyOnUnmount: false
})(NewPost)

如果这对您没有帮助,请提供有关您如何使用组件的更好的上下文。

更新: 我做了一个例子,我定义了 4 个组件:

  • NewPost.js:是与redux-form.
  • 店铺关联的形式
  • ShowPost.js:显示当您点击提交按钮时表单捕获的内容(post)。此数据设置为 NewPost 内部状态,然后作为 prop 传递。
  • ShowPostFromSelector.js:显示表单捕获的内容,这是由于使用了选择器 formValueSelector
  • App.js:是上面3个组件的容器,定义了onSubmit函数。

这里是: https://codesandbox.io/s/w06kn56wqk