2016-08-10 3 views
10

redux-form을 사용하여 초기 양식 필드 값을 설정하는 데 문제가 있습니다.Redux 양식 - 상태로 업데이트되지 않는 initialValues ​​

저는 redux-form v6.0.0-rc.3을 사용하고 있으며 v15.3.0에 반응합니다.

여기 내 문제가 있습니다. 사용자 격자가 있고 사용자 행을 클릭하면 사용자 편집 페이지로 이동하고 URL에 사용자 ID를 포함합니다. 그런 다음 사용자 편집 페이지에서 id를 잡고 this.state.users를 반환하는 작업 생성자 인 fetchUser (this.props.params.id)를 호출합니다.

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

내 이해함으로써, 이것은 initialValues이 state.users.user로 설정해야하며,이 상태가 업데이트 될 때마다 initialValues도 업데이트해야합니다 : 그때 호출하여 양식 inital 값을 설정하려고 시도하고있다. 이것은 나를위한 것이 아닙니다. InitialValues는 이전에 클릭 된 사용자 행 (즉, this.state.users.user의 이전 상태)으로 설정됩니다. 그래서 나는 이것을 테스트하고이 구성 요소에 단추를 추가하고 내가 사용자 ID로 다시 fetchUser를 호출하고 클릭하면 하드 코딩하기로 결정

this.props.fetchUser('75e585aa-480b-496a-b852-82a541aa0ca3');

이 올바르게 상태를 업데이트하고 있지만 initialValues에 대한 값 바뀌지 않는다. 상태가 업데이트되면 업데이트되지 않습니다. 나는 똑같은 프로세스를 이전 버전의 redux-form에서 테스트했고 예상대로 작동했다.

여기에 뭔가 잘못되었거나 사용중인 버전의 문제입니다.

사용자 편집 양식 -

class UsersShowForm extends Component { 

    componentWillMount() { 
     this.props.fetchUser(this.props.params.id); 
    } 

    onSubmit(props){ 
     console.log('submitting'); 
    } 

    changeUser() { 
     this.props.fetchUser('75e585aa-480b-496a-b852-82a541aa0ca3'); 
    } 

    renderTextField(field) { 
     return (
     <TextField 
     floatingLabelText={field.input.label} 
     errorText={field.touched && field.error} 
     fullWidth={true} 
     {...field.input} 
     />) 
    } 

    render() { 
     const { handleSubmit, submitting, pristine } = this.props; 

     return(

      <div> 
       <form onSubmit={handleSubmit(this.onSubmit.bind(this))} className="mdl-cell mdl-cell--12-col"> 

        <Field name="emailAddress" component={this.renderTextField} label="Email Address"/> 

        <Field name="firstName" component={this.renderTextField} label="First Name"/> 

        <Field name="lastName" component={this.renderTextField} label="Last Name"/> 
       </form> 

       <RaisedButton onClick={this.changeUser.bind(this)} label="Primary" primary={true} /> 
      </div> 

     ); 
    } 
} 

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

UsersShowForm = reduxForm({ 
    form: 'UsersShowForm' 
})(UsersShowForm) 

UsersShowForm = connect(
    mapStateToProps, 
    actions    
)(UsersShowForm) 

export default UsersShowForm 

사용자 감속기 -

import { 
    FETCH_USERS, 
    FETCH_USER 
} from '../actions/types'; 

const INITIAL_STATE = { all: [], user: {} }; 

export default function(state = { INITIAL_STATE }, action) { 
    switch (action.type) { 
     case FETCH_USERS: 
      return {...state, all: action.payload }; 
     case FETCH_USER: 
      return {...state, user: action.payload }; 
     default: 
      return state; 
    } 

} 

감속기 색인 -

import { combineReducers } from 'redux'; 
import { reducer as formReducer } from 'redux-form'; 
import usersReducer from './users_reducer'; 

const rootReducer = combineReducers({ 
    form: formReducer, 
    users: usersReducer 
}); 

export default rootReducer; 
+0

의 완벽한 예를 찾을 수 있습니다. NPM에서 빌드 할 때 오류가 있습니까? – Martin

+0

무슨 뜻인지 확실하지 않습니다. 내 감속기를 내 보낸 다음 색인에서 가져 오기 - './users_reducer'에서 usersReducer를 가져옵니다. 오류가 발생하지 않으며 사용자 축소 기가 다른 모든 시나리오에서 예상대로 작동합니다. –

+0

내 말은 '기본 함수 내보내기'를 사용하면 함수 이름을 지정하지 않는 것입니다. 색인 감속기가 사용할 기본 함수 usersReducer()를 보려고합니다. – Martin

답변

23

내가 REDUX 형식 V6.0.0에 업데이트 후 같은 문제에 직면했다 -rc.4.

내가 자원의 데이터와 redux-form 형태를 미리 채우려면 사실

UsersShowForm = reduxForm({ 
    form: 'UsersShowForm', 
    enableReinitialize: true 
})(UsersShowForm) 
+1

그게 문제를 해결했습니다! 나는 그것을 디버깅하는 데 많은 시간을 보냈다. 감사. –

+0

또한 문제를 해결했습니다 ... 문서에도 쓰여 있습니다 : http://redux-form.com/6.4.3/examples/initializeFromState/ –

+0

또한이 문제를 해결하는 데 많은 시간을 보냈습니다. 문서에서 좀 더 명확해야합니다. 감사합니다 – InfoStatus

2

에 enableReinitialize 설정 해결, 당신은 reduxForm 커넥터 구성 요소/컨테이너를 장식 할 때 자동으로 읽을 수있는 initialValues 소품을 사용 . initialValues의 키가 양식 필드의 name과 일치해야합니다.

참고 : reduxForm() 데코레이터를 먼저 적용한 다음 connect()을 redux에서 적용해야합니다. 다른 방법으로는 작동하지 않습니다.

REDUX 형식 7.2.3 사용 : 공식 문서에서

const connectedReduxForm = reduxForm({ 
form: 'someUniqueFormId', 
    // resets the values every time the state changes 
    // use only if you need to re-populate when the state changes 
    //enableReinitialize : true 
})(UserForm); 

export default connect(
    (state) => { 
    // map state to props 
    // important: initialValues prop will be read by redux-form 
    // the keys must match the `name` property of the each form field 
    initialValues: state.user 
    }, 
    { fetchUser } // map dispatch to props 
)(connectedReduxForm) 

: 소품이나 reduxForm initialValues ​​제공

값() 구성 매개 변수의 형식은 상태로로드됩니다 그 이후에 "깨끗한"것으로 취급됩니다.또한 reset()이 전달 될 때 반환되는 값이됩니다. "초기 값"을 저장하는 것 외에도 양식을 초기화하면 기존 값을 덮어 씁니다.

자세한 내용은 당신이 당신의 인덱스 존재 나던 그 그것으로 usersReducer 수입하지 감속기에 가져올 때 사용자 감속기는 그래서 이름이없는 official documentation

관련 문제