【发布时间】:2018-05-08 13:29:18
【问题描述】:
我在使用 redux-form 时遇到问题。我正在标准 CRUD 应用程序中创建更新/编辑页面,但我似乎无法让表单获取其初始值。这是我的代码:
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { updateArtwork, fetchPiece } from '../actions';
class UpdateArtwork extends Component {
componentDidMount() {
const { id } = this.props.match.params;
this.props.fetchPiece(id);
}
renderField(field) {
return (
<div className="input-field">
<input
placeholder={field.label}
type="text"
{...field.input}
/>
</div>
);
}
onSubmit(values) {
const { updateArtwork, history } = this.props;
const { id } = this.props.match.params;
updateArtwork(id, values, history);
}
render() {
const { handleSubmit, piece } = this.props;
return (
<div className="card-panel">
<h4>Edit this piece.</h4>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
label="Artwork URL"
name="image"
component={this.renderField}
/>
<Field
label="Artist"
name="artist"
component={this.renderField}
/>
<Field
label="Class"
name="teacher"
component={this.renderField}
/>
<Field
label="Grade"
name="level"
component={this.renderField}
/>
<Field
label="Description"
name="description"
component={this.renderField}
/>
<button
type="submit"
className="waves-light waves-effect btn"
>
Submit
</button>
<Link
to={`/artwork/show/${piece._id}`}
style={{ margin: '0 5px' }}
className="waves-light waves-effect btn"
>
Cancel
</Link>
</form>
</div>
);
}
}
const mapStateToProps = ({ artwork }, ownProps) => {
return {
piece: artwork[ownProps.match.params._id],
initialValues: artwork[ownProps.match.params._id]
};
};
export default reduxForm({
form: 'UpdateArtworkForm',
enableReinitialize: true
})(
connect(mapStateToProps, { updateArtwork, fetchPiece })(withRouter(UpdateArtwork))
);
我在在线搜索中发现的最常见问题是在我的 mapStateToProps 函数中包含 initialValues 属性,并在我的 reduxForm 配置中包含“enableReinitialize: true”。我已经完成了这两项,但我仍然没有得到。
附带说明,此组件中的所有其他内容都有效。该片段会随着更新后的输入中的任何内容正确更新,并且我的 fetchPiece() 操作正在正确地获取片段,就像它在显示页面中所做的一样。所有正确的信息都位于我的网络选项卡中的一个对象中。我似乎无法将其加载到表单中。
我在这里错过了什么?
编辑:artifact[ownProps.match.params._id] 返回以下内容:
{_id: "5a15ecb8d6cfbe0c4e68b3be", artist: "Ceanne", teacher: "Royals", level: "14", description: "Derek and Ceanne at the Royals game.", …}
artist: "Ceanne"
comments: (3) [{…}, {…}, {…}]
created: "2017-11-22T21:31:36.849Z"
description: "Derek and Ceanne at the Royals game."
image: "https://res.cloudinary.com/drkgrntt/image/upload/v1511386296/raixtyabfjrosvnnfavs.jpg"
level: "14"
teacher: "Royals"
__v: 8
_id: "5a15ecb8d6cfbe0c4e68b3be"
__proto__: Object
【问题讨论】:
-
你能显示
artwork[ownProps.match.params._id]返回什么 -
我刚刚添加了它并进行了编辑。
标签: reactjs redux react-redux redux-form