【发布时间】:2019-04-17 09:53:10
【问题描述】:
最初显示页面时,我无法在字段中填充数据...
我的假设是,如果我定义了 finYear,那么它会自动使用 finYear 中的属性名称并将其映射到 <Field name="totalFixedAssets"> 属性?
import React from "react";
import { Field, reduxForm } from "redux-form";
import { fetchFinancialYear } from "../actions/financialYearActions";
import { connect } from "react-redux";
class FirstForm extends React.Component {
componentDidMount() {
this.props.dispatch(fetchFinancialYear(this.props.match.params.id));
}
render() {
return (
<form>
<div>
<div>{this.props.finYear.totalFixedAssets}</div>
<label>Total Fixed Assets</label>
<Field name="totalFixedAssets" component="input" />
</div>
</form>
);
}
}
const mapStateToProps = state => ({
finYear: state.financialYearReducer.financialYear
});
const mapDispatchToProps = dispatch => ({
// ...
});
FirstForm = reduxForm({
form: "firstForm"
})(FirstForm);
export default connect(
mapStateToProps,
mapDispatchToProps // bind account loading action creator
)(FirstForm);
reducer 代码...
import {
FETCH_FINANCIAL_YEAR_BEGIN,
FETCH_FINANCIAL_YEAR_SUCCESS,
FETCH_FINANCIAL_YEAR_FAILURE
} from "../actions/financialYearActions";
const initialState = {
financialYear: {},
loading: false,
error: null
};
function financialYearReducer(state = initialState, action) {
switch (action.type) {
case FETCH_FINANCIAL_YEAR_BEGIN:
return {
...state,
loading: true,
error: null
};
case FETCH_FINANCIAL_YEAR_SUCCESS:
return {
...state,
loading: false,
financialYear: action.payload.financialYear
};
case FETCH_FINANCIAL_YEAR_FAILURE:
return {
...state,
loading: false,
error: action.payload.error,
financialYear: {}
};
default:
return state;
}
}
export default financialYearReducer;
动作代码...
import axios from "axios";
export const FETCH_FINANCIAL_YEAR_BEGIN = "FETCH_FINANCIAL_YEAR_BEGIN";
export const FETCH_FINANCIAL_YEAR_SUCCESS = "FETCH_FINANCIAL_YEAR_SUCCESS";
export const FETCH_FINANCIAL_YEAR_FAILURE = "FETCH_FINANCIAL_YEAR_FAILURE";
export const fetchFinancialYearBegin = () => ({
type: FETCH_FINANCIAL_YEAR_BEGIN
});
export const fetchFinancialYearSuccess = financialYear => ({
type: FETCH_FINANCIAL_YEAR_SUCCESS,
payload: { financialYear }
});
export const fetchFinancialYearFailure = error => ({
type: FETCH_FINANCIAL_YEAR_FAILURE,
payload: { error }
});
export function fetchFinancialYear(financialYearUuid) {
return dispatch => {
dispatch(fetchFinancialYearBegin());
const accountRequest = {
financialYearUuid: financialYearUuid,
userUuid: "asdf"
};
return axios
.post("/account/service/fetch/single", accountRequest)
.then(res => {
dispatch(fetchFinancialYearSuccess(res.data.financialYear));
return res.data;
})
.catch(error => dispatch(fetchFinancialYearFailure(error)));
};
}
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
我已成功从 API 调用返回数据,我可以将其显示在表单上的 <div>{this.props.finYear.totalFixedAssets}</div> 中,虽然我试图在表单中显示 <Field name="totalFixedAssets" component="input" /> 中的值,但它始终为空白。
【问题讨论】:
标签: reactjs redux redux-form