我使用的是redux-form,我已经成功地使用其初始值来预先填充了我的表单。
如果可以输入一个值(即ID)是一项很好的功能,那么如果输入了匹配的ID,则会带回与该ID相关的所有数据。我一直在寻找有人这样做的示例,但没有发现任何东西。
我有这个演示,理想情况下,输入ID后,它会(通过下拉菜单)返回匹配的ID。选择后,将填充表格。
https://codepen.io/anon/pen/WaMywg
const { Component } = React;
const { Provider, connect } = ReactRedux;
const {
createStore,
applyMiddleware
} = Redux;
const {
Field,
Control,
Form,
combineForms,
actions
} = ReactReduxForm;
const thunk = ReduxThunk.default;
const logger = reduxLogger();
const initialUserState = {
firstName: '',
lastName: '',
};
const randomUsers = [
{firstName: "John", lastName: "Snow", id: "123"},
{firstName: "Bilbo", lastName: "Baggins", id: "456"},
{firstName: "Super", lastName: "Mario", id: "789"},
{firstName: "Arthur", lastName: "Dent", id: "101112"},
];
const store = createStore(combineForms({
user: initialUserState,
}), applyMiddleware(thunk));
class UserForm extends Component {
handleSubmit(values) {
console.log(values);
}
changeUser() {
this.props.setDefaultUser(
randomUsers[Math.floor(Math.random()*randomUsers.length)]
)
}
render() {
return (
<Form
model="user"
onSubmit={(values) => this.handleSubmit(values)}
>
<div className="field">
<label>First name:</label>
<Control.text model="user.firstName" />
</div>
<div className="field">
<label>Last name:</label>
<Control.text model="user.lastName" />
</div>
<div className="field">
<label>ID:</label>
<Control.text model="user.id" />
</div>
<button type="submit">
Submit
</button>
<br/>
<button onClick={this.changeUser.bind(this)}>
Change Defaults
</button>
</Form>
)
}
}
const mapDispatchToProps = {
setDefaultUser: (values) => actions.merge('user', values)
}
const ConnectedForm = connect(null, mapDispatchToProps)(UserForm);
class App extends React.Component {
render() {
return (
<Provider store={store}>
<ConnectedForm />
</Provider>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));