如何从状态填充Redux-Form选择/下拉列表

时间:2018-01-20 15:08:42

标签: reactjs redux redux-form

从州填充选择/下拉列表的最佳做法是什么?

我填充了像这样的redux-form ......

import React from 'react';
import { connect } from 'react-redux';  
import { Field, reduxForm } from 'redux-form';  
import FormItem from '../FormItem.js';
import FormFooter from '../../components/FormFooter.js';
import Button from '../../components/Button.js';

let UserForm = props => {

  const { handleSubmit, onSubmit } = props;

    return (
    <form onSubmit={handleSubmit(onSubmit)}>

            <FormItem
                label = { <label htmlFor="firstName">First Name</label> }
                field = { <Field name="firstName" type="text" placeholder="First name" component="input" className="w-full"/>} 
            />

            <FormItem
                label = { <label htmlFor="lastName">Last Name</label> }
                field = { <Field name="lastName" type="text" placeholder="Last name" component="input" className="w-full"/> }
            />

            <FormFooter
                left={ <Button href="/users" icon="fa-ban" text="Cancel" /> }
                right={ <button type="submit">Save</button> }
            />

        </form>
    )
}

UserForm = reduxForm({
  form: 'userForm'
})(UserForm)

function mapStateToProps(state) {  
  return { initialValues: state.user.data }
}

UserForm = connect(mapStateToProps
)(UserForm)

export default UserForm

这是包含该表单并获取数据的文件:

import React from 'react';
import { connect } from 'react-redux';  
import PageHeaderBar from '../../components/PageHeaderBar.js';
import PageWrapper from '../PageWrapper.js';
import ContentWrapper from '../ContentWrapper.js';
import { loadUser, updateUser } from '../../actions/users';
import UserAccountForm from './UserAccountForm';
import { Values } from "redux-form-website-template";

class UserAccount extends React.Component {

  constructor(props) {
    super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
        this.props.loadUser(localStorage.getItem('userId'));
  }

  handleSubmit(formProps) {
    this.props.updateUser(formProps);
  }

  render() {

    return (

      <PageWrapper>

        <PageHeaderBar title="User profile" />

        <ContentWrapper>
                    <UserAccountForm onSubmit={this.handleSubmit} />
                    <Values form="userForm" />
        </ContentWrapper>

      </PageWrapper>
    );
  }
}

export default connect(null, { loadUser, updateUser })(UserAccount);  

Root reducer:

import { combineReducers } from 'redux';  
import { reducer as formReducer } from 'redux-form';  
import authReducer from './auth_reducer';
import userReducer from './user_reducer';
import categoryReducer from './user_reducer';

const rootReducer = combineReducers({  
  auth: authReducer,
  form: formReducer,
  user: userReducer.
  category: categoryReducer
});

export default rootReducer; 

用户缩减器:

import { LOAD_USER_SUCCESS, LOAD_USERS_SUCCESS } from '../actions/types';

const INITIAL_STATE = { data: {} }

export default function (state = {}, action) {  
  switch(action.type) {
    case LOAD_USER_SUCCESS:
      return { ...state, data: action.data };
    case LOAD_USERS_SUCCESS:
      console.log('LOAD_USER_SUCCESS');
      return { ...state, data: action.data };
    default:
      return state;
  }
}

现在我想使用以下组件向上面的表单添加一个select,并从state.category.data填充它的值。这是我到目前为止所拥有的......

import React from 'react';
import { connect } from 'react-redux';  
import { loadCategories } from '../../actions/categories';
import { Field, reduxForm } from 'redux-form';  
import FormItem from '../FormItem.js';
import VirtualizedSelect from 'react-virtualized-select'
import 'react-datepicker/dist/react-datepicker.css';

export const renderSelect = (field) => (
  <VirtualizedSelect
    onChange={field.input.onChange}
    optionHeight={35}
    value={field.input.value}
  />
);

class CategorySelects extends React.Component {

  constructor(props) {
    super(props);
    console.log( 'props' );
    console.log( props.data );
  }

  render() {
    return (
      <FormItem
        label = { <label htmlFor="type">Category</label> }
        field = { <Field name="type" component={renderSelect} onChange={this.handleTypeChange} /> }
      />
    );
  }
}

export default CategorySelects

我将其添加到表单中:

<CategorySelects name="categories" />

我不确定如何填充选择。现在我只使用state.user.data在UserForm上设置initialValues。我是否还需要在state.category.data中合并,或者我是否以错误的方式进行此操作?谢谢!

1 个答案:

答案 0 :(得分:1)

我可能误解了您的一些代码,但我认为您的问题是name

中的硬编码CategorySelects
<Field name="type" component={renderSelect} onChange={this.handleTypeChange} />

因为您在通过时添加表单时传递了名称     

然后Field上的CategorySelects应该是这样的

<Field name={props.name} component={renderSelect} onChange={this.handleTypeChange}/>

假设您的initialValues看起来像

{firstName: "Bob", lastName: "Smith", categories: [10, 20, 30] }

这将确保您的选项被选中,但我不知道您是如何将选项推送到组件中的。

如果填写了您想要弄清楚的选项,那么是的,您需要将state.category.data推送到您的组件中,但我不会通过redux-form执行此操作,我只会通过该数据作为CategorySelects的道具,然后通过您的VirtualizedSelect函数将其传递给renderSelect

如果用户数据看起来像这样,那么忽略我答案的第一部分:

{firstName: "Bob", lastName: "Smith", type: 10 }

长期和短期是redux-form将帮助您管理表单的value,但您可以使用与非redux表单相同的方式处理选项。

以下是redux-form网站

中的示例
<Field name="favoriteColor" component="select">
    <option />
    <option value="#ff0000">Red</option>
    <option value="#00ff00">Green</option>
    <option value="#0000ff">Blue</option>
</Field>

如果您的初始值对象为{favoriteColor: "#00ff00"},则在呈现组件时将选择绿色。