如何使用 redux-form 和 reselect

How to use redux-form with reselect

我想使用 reselect with redux-form 从 redux 中获取值。问题是我不知道如何将 getFormValues 与重新选择结合起来。似乎我无法访问 createSelector 中的状态。这样我就无法想出在重新选择中使用 redux-form 的选择器的方法。

例如:

// How to access the state here?
const getFoo = createSelector(
  [getBar],
  (bar) => {
    // return something
  }
)

redux 中的选择器是这样工作的:

getFormValues('formName')(state);

您可能希望将重新选择与 redux-form 的选择器一起使用(这是您从 redux-form 中获取当前数据的方式)。

您可以在此处了解有关选择器的更多信息....

https://redux-form.com/7.3.0/docs/api/formvalueselector.md/

这里有一个例子...

https://redux-form.com/7.3.0/examples/selectingformvalues/

然后您将使用带有 Redux-form 选择器的 Reselect 选择器,类似于这样...

const selector = formValueSelector('myForm');
const mapStateToProps = createStructuredSelector({
  firstValue: (state) => selector(state, 'firstValue')
});

这是另一个从不同的 Github 相关主题中使用的示例 https://github.com/erikras/redux-form/issues/1505

const formSelector = formValueSelector('myForm')
const myFieldTitle = (state) => formSelector(state, 'title')
const doSomethingWithTitleSelector = createSelector(myFieldTitle, (title) => {
    return doSomethingWithTitle(title)
})

function doSomethingWithTitle() { ... }

const Form = reduxForm({
    form: 'myForm',
})(TheComponent)

export default connect(
    state => ({
        titleWithSomethingDone: doSomethingWithTitleSelector(state)
    })
)(Form)

直到最近,尝试以独立于形式的方式获取 select 状态真的很糟糕。 我通过 PRing 一个 <FormName> 组件纠正了这种情况,该组件允许您获取封闭表单元素的名称,并创建了一个库 redux-form-reselect 以适应 redux-form select 或。例如:

// @flow

import * as React from 'react'
import {connect} from 'react-redux'
import {
  isSubmitting,
  hasSubmitSucceeded,
  hasSubmitFailed,
  getFormError,
  FormName,
} from 'redux-form'
import {createStructuredFormSelector} from 'redux-form-reselect'
import SubmitStatus from './SubmitStatus'

type Props = {
  submitting: boolean,
  submitSucceeded: boolean,
  submitFailed: boolean,
  error: ?Error,
}

export default class SubmitStatusContainer extends React.Component<Props> {
  ConnectedSubmitStatus = connect(createStructuredFormSelector({
    // createStructuredFormSelector converts all of these selectors
    // to use the form name passed as the `form` prop to
    // ConnectedSubmitStatus.
    submitting: isSubmitting,
    submitSucceeded: hasSubmitSucceeded,
    submitFailed: hasSubmitFailed,
    error: getFormError,
  }))(SubmitStatus)

  render(): ?React.Node {
    const {ConnectedSubmitStatus} = this
    return (
      <FormName>
        {({form}) => <ConnectedSubmitStatus {...this.props} form={form} />}
      </FormName>
    )
  }
}

您可以像这样使用 getFormValues:

import { createSelector } from 'reselect';
import { getFormValues } from 'redux-form';

const selectFormValues = () => createSelector(
  (state) => state,
  (state) => getFormValues('formName')(state)
);