我有一个NewGroup
组件,它对后端进行POST调用。返回调用时,将相应地调度操作,并由reducer更新应用程序状态。
BUT!组件NewGroup
不知道新创建的实体的ID,以便在更新状态下查找它。
我应该如何处理这种情况?
一些代码:
这是减速器:
import { FETCH_GROUPS_SUCCESS, FETCH_GROUPS_ERROR, CREATE_GROUP_SUCCESS, CREATE_GROUP_ERROR, DELETE_GROUP, FETCH_GROUP_SUCCESS, FETCH_GROUP_ERROR } from '../actions/creators';
export const FULL_GROUP = 'full_group';
export const SNIPPET_GROUP = 'snippet_group';
const INITIAL_STATE = {
data: null,
isLoading: true,
errorFetching: null
};
export default function(state=INITIAL_STATE, action) {
switch(action.type) {
case FETCH_GROUPS_SUCCESS:
return {
data: _.zipObject(_.map(action.payload, group => group.id),
_.map(action.payload, group => ({
data: group,
isLoading: true,
errorFetching: null,
mode: SNIPPET_GROUP
}))
),
isLoading: false,
errorFetching: null
};
case FETCH_GROUPS_ERROR:
return {
data: null,
isLoading: false,
errorFetching: action.payload.error
};
case CREATE_GROUP_SUCCESS:
return { ...state, [action.payload.id]: {
data: action.payload,
isLoading: true,
errorFetching: null,
mode: SNIPPET_GROUP
}};
case CREATE_GROUP_ERROR:
return { ...state, [action.payload.id]: {
data: null,
isLoading: false,
errorFetching: action.payload.error
}};
default:
return state;
}
}
这是NewGroup
组件:
class NewGroup extends Component {
_onSubmit(values) {
this.props.createGroup(values);
}
render() {
const { handleSubmit } = this.props;
//id of the newly created/errored entity on the backend is unknown and there was it cannot be accessed here.
return (
<div>
<form onSubmit={handleSubmit(this._onSubmit.bind(this))}>
<Field name="name" label="Name" type="text" fieldType="input" component={renderField.bind(this)}/>
<Field name="description" label="Description" type="text" fieldType="input" component={renderField.bind(this)}/>
<button type="submit" className="btn btn-primary">Create</button>
<button type="button" className="btn btn-primary" onClick={() => this.props.history.push('/group')}>Cancel</button>
</form>
</div>
);
}
}
export default reduxForm({
validate,
//a unique id for this form
form:'NewGroup',
validators
})(
connect(null, { createGroup })(NewGroup)
);
这是redux-form
的事实在这里并不重要。
答案 0 :(得分:1)
您可以将id存储在redux存储中(例如,newAddedSomethingId:'yourID',创建后,POST成功,发送另一个操作(或者你甚至可以在同一个reducer中执行,取决于你的方式)它设置)存储id然后将其传递给组件。这样,一旦redux商店中的值从POST更新,你的组件将重新渲染,因此你的组件知道ID。