使用Redux-Form中initializingFromState的示例,我试图动态设置它。这是在书籍列表中编辑特定书籍,并使用在express.js中设置的简单api。
完整的容器在下面。我不知何故需要在initialValues
函数中传递mapStateToProps
。在示例中,这是通过静态对象完成的,但是我无法弄清楚如何使用通过fetchBook
提取的信息,并将其传递给initialValues
。
容器:
import React, { Component, PropTypes } from 'react';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { fetchBook, editBook } from '../actions/index';
class BookEdit extends Component {
componentWillMount() {
this.props.fetchBook(this.props.params.id);
}
static contextTypes = {
router: PropTypes.object
}
onSubmit(props) {
this.props.editBook(this.props.book.id, props)
.then(() => {
this.context.router.push('/');
});
}
const data = {
title: {this.props.book.title},
description: {this.props.author}
}
render() {
const { fields: { title, author }, handleSubmit } = this.props;
const { book } = this.props;
if (!book) {
return (
<div>
<p>Loading...</p>
</div>
)
}
return (
<div>
<Link to="/">Back</Link>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<h2>Add a new book</h2>
<label>Title</label>
<input type="text" {...title} />
<div className="text-help">{title.touched ? title.error : ''}</div>
<label>Author</label>
<input type="text" {...author} />
<div className="text-help">{author.touched ? author.error : ''}</div>
<button type="submit">Add</button>
<Link to="/" className="button">Go back</Link>
</form>
</div>
);
}
}
function mapStateToProps(state) {
return {
book: state.books.book,
initialValues: // how do I pass in the books here?
};
}
export default reduxForm({
form: 'EditBookForm',
fields: ['title', 'author']
}, mapStateToProps, { fetchBook, editBook })(BookEdit);
谢谢你。
最佳答案
您的表单值不是state.books.book
中的值吗?我认为这就是您要寻找的全部:
function mapStateToProps(state) {
return {
book: state.books.book,
initialValues: state.books.book
};
}
由于您实际上只是在查看
this.props.book
来了解它是否已加载,因此更明确地执行以下操作:function mapStateToProps(state) {
return {
loaded: !!state.books.book,
initialValues: state.books.book
};
}
希望能有所帮助。