我想使用redux-form重新选择来从redux中获取值。问题是我不知道如何将getFormValues与reselect结合起来。似乎我无法访问createSelector中的状态。这样我就无法在重新选择中使用redux-form的选择器。
例如:
// How to access the state here?
const getFoo = createSelector(
[getBar],
(bar) => {
// return something
}
)
redux中的选择器的工作方式如下:
getFormValues('formName')(state);
答案 0 :(得分:2)
您可能希望使用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)
答案 1 :(得分:1)
您可以像这样使用 getFormValues:
import { createSelector } from 'reselect';
import { getFormValues } from 'redux-form';
const selectFormValues = () => createSelector(
(state) => state,
(state) => getFormValues('formName')(state)
);
答案 2 :(得分:0)
直到最近,尝试以与表格无关的方式获取选择状态确实很烂。
我通过PR <FormName>
组件纠正了这种情况,该组件使您能够获取封闭的form元素的名称,并创建了一个库redux-form-reselect
用于改编redux-form选择器。例如:
// @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>
)
}
}