【发布时间】:2017-03-05 18:13:01
【问题描述】:
我是 React 新手,所以我尝试在这里展示尽可能多的代码,希望能解决这个问题!基本上我只想用从另一个 API 获取的对象的属性填充表单字段。对象存储在 autoFill reducer 中。例如,我想用 autoFill.volumeInfo.title 填充输入,用户可以根据需要在提交之前更改值。
我使用了来自 autoFill 操作创建器的 mapDispatchtoProps,但 this.props.autoFill 在 FillForm 组件中仍然显示为未定义。我也对如何再次使用道具来提交表单感到困惑。谢谢!
我的减速机:
import { AUTO_FILL } from '../actions/index';
export default function(state = null, action) {
switch(action.type) {
case AUTO_FILL:
return action.payload;
}
return state;
}
动作创建者:
export const AUTO_FILL = 'AUTO_FILL';
export function autoFill(data) {
return {
type: AUTO_FILL,
payload: data
}
}
调用自动填充动作创建者:
class SelectBook extends Component {
render() {
return (
....
<button
className="btn btn-primary"
onClick={() => this.props.autoFill(this.props.result)}>
Next
</button>
);
}
}
....
function mapDispatchToProps(dispatch) {
return bindActionCreators({ autoFill }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(SelectBook);
这是问题所在的实际表格:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import { createBook } from '../actions/index;
class FillForm extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
}
onSubmit(props) {
this.props.createBook(props)
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
const { fields: { title }, handleSubmit } = this.props;
return (
<form {...initialValues} onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<input type="text" className="form-control" name="title" {...title} />
<button type="submit">Submit</button>
</form>
)
}
export default reduxForm({
form: 'AutoForm',
fields: ['title']
},
state => ({
initialValues: {
title: state.autoFill.volumeInfo.title
}
}), {createBook})(FillForm)
【问题讨论】:
-
您说“this.props.autoFill”在 FillForm 中未定义,但我没有看到它在那里使用。您真的是指 SelectBook 中的吗?
-
@BrandonRoberts 我在这里添加了一个带有新代码/新问题的新问题......也许它更清楚一点。谢谢! stackoverflow.com/questions/42624225/…
标签: forms reactjs react-redux redux-form react-redux-form