我在使用 redux-form 设置初始表单字段值时遇到一些问题。
我正在使用 redux-form v6.0.0-rc.3 和 React v15.3.0。
所以这是我的问题,我有一个用户网格,当单击用户行时,我将导航到编辑用户页面并将用户 ID 包含在 url 中。然后在编辑用户页面上,我获取 id 并调用 fetchUser(this.props.params.id),它是一个返回 this.state.users 的操作创建者。然后我尝试通过调用设置表单初始值:
function mapStateToProps(state) {
return { initialValues: state.users.user }
}
据我了解,这应该将initialValues设置为state.users.user,并且每当更新此状态时,initialValues也应该更新。我的情况并非如此。 InitialValues 被设置为先前单击的用户行(即 this.state.users.user 的先前状态)。所以我决定对此进行测试并向该组件添加一个按钮,当单击它时,我将使用硬编码的用户 ID 再次调用 fetchUser:
this.props.fetchUser('75e585aa-480b-496a-b852-82a541aa0ca3');
这会正确更新状态,但初始值的值不会更改。当状态更新时它不会更新。我在旧版本的 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;