我有一个redux应用程序,可以让用户发布一些东西(比如只包含标题和正文的博客文章)。用户可以随时编辑帖子。我无法更新缩减器,即。我只想更新特定<strong>“id”的标题和正文。我正在尝试更新 reducer 中的状态,如下所示:
case SUBMIT_POST:
let id = action.payload.id;
return {
...state,
[id]: {
...state[id],
title: action.payload.title,
body: action.payload.body
}
};
我的动作创建者看起来像这样:
//Action creator for submitting edited post
export function submitEditedPost(id, values, callback) {
const request = axios.put(`${API}/posts/${id}`, {values}, {headers});
return dispatch => {
return request.then((res) => {
callback();
console.log(res.data.values)
dispatch({
type:SUBMIT_POST,
payload: res.data.values
})
})
}
}
如何使用针对该特定帖子ID的新编辑的标题和正文更新reducer?
编辑1:
我正在以 onSubmit()方式调用动作创建者,如下所示:
onSubmit(values) {
const { id } = this.props.match.params;
const formData = {};
for (const field in this.refs) {
formData[field] = this.refs[field].value;
}
formData.id = id;
console.log('-->', formData);
this.props.submitEditedPost(id, formData, () => {
this.props.history.push('/');
});
}
编辑2: reducer中操作的屏幕截图如下所示:
编辑3:我的整个减速机:
import _ from 'lodash';
import { FETCH_POSTS, FETCH_POST, CREATE_POST, EDIT_POST, SUBMIT_POST } from '../actions/posts_action';
export default function(state = {posts: {} }, action) {
switch (action.type) {
case FETCH_POST:
// const post = action.payload.data;
// const newState = { ...state, };
// newState[post.id] = post;
// return newState;
return {...state, [action.payload.id]: action.payload};
case FETCH_POSTS:
return {posts: { ...state.posts, ...(_.mapKeys(action.payload,'id'))}};
case CREATE_POST:
return {...state, [ action.payload.id]: action.payload};
case EDIT_POST:
return { ...state, [action.payload.id]: action.payload};
case SUBMIT_POST:
console.log(action.payload);
let id = action.payload.id;
return {
...state,
[id]: {
...state[id],
title: action.payload.title,
body: action.payload.body
}
};
default:
return state;
}
}
编辑4 :redux-dev-tools的屏幕截图: