首页 文章

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

提问于
浏览
3

我使用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

我发现了同样的问题here但它没有帮助我 .

1 回答

  • 6

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

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

    如果您的 NewPost 组件随时卸载,可能通过在导航期间更改视图或其他内容,表单的状态将被破坏 . 您可以通过将 destroyOnUnmount 属性与 false 值添加到reduxForm包装器来避免此类默认行为:

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

    如果这对您没有帮助,请提供有关如何使用组件的更好背景信息 .

    UPDATE: 我举了一个例子来定义4个组件:

    • NewPost.js :这是使用redux-form连接到商店的表单 .

    • ShowPost.js :显示按下提交按钮时表单捕获的内容(帖子) . 此数据设置为NewPost内部状态,然后作为prop传递 .

    • ShowPostFromSelector.js :显示表单捕获的内容,这是由于使用了选择器formValueSelector .

    • App.js :它是上面3个组件的容器,其中定义了onSubmit函数 .

    Here it is: https://codesandbox.io/s/w06kn56wqk

相关问题