如何在另一个组件中获取 Redux 表单数据

How to get Redux Form data in another Component

如何从 redux 表单传递数据,以便我可以在 App.js 中访问该数据? 这是我使用 redux-form.after 编写的代码 我点击提交数据应该从 form.js 传递到 app.js。并且数据应该显示在页面上。

这里是form.js-

const Form=({fields:{name,address}})=>(
  <form>
    <center>
    <div>
      <label>First Name</label>
      <Field type="text" component="input" placeholder="Name" name="name"/>
    </div>
    <div>
      <label>Address</label>
      <Field type="text" component="input" placeholder="Phone" name="phone" />
    </div>
    <button type="submit">Submit</button>
  </center>
  </form>
)


export default reduxForm({
  form: 'form',
  fields: ['name', 'address']
})(Form);

如何将输入的数据传递给 app.js?

您需要做的是使用 getFormValues 获取 redux field

所以在App.js你可以有

import {getFormValues} from 'redux-form';

..
const App = (props) => {
      var {name, phone} = props.formStates
      console.log(name, phone);
}

function mapStateToProps(state) {
    return {
         formStates: getFormValues('form')(state) // here 'form' is the name you have given your redux form 
    }
}

export default connect(mapStateToProps)(App)

上面提到的答案是绝对正确的,但是,当您的表单组件被卸载时,状态可能会被破坏,然后它将无法在任何其他 component.To 解决这个问题,您可以添加 destroyOnUnmount: false像这样到你的 reduxForm 包装器

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

现在你可以按照上面的回答获取任意组件中的表单数据了。希望这有帮助