如何使状态可迭代并解决“未处理的拒绝(TypeError):state.story 不可迭代"? [英] How to make state iterable and resolve "Unhandled Rejection (TypeError): state.story is not iterable"?
问题描述
我通过 redux 和 axios 将一些文件和一些其他数据发送到我的后端.但是,当我这样做时,我收到以下错误消息 Unhandled Rejection (TypeError): state.story is not iterable
.虽然错误发生在我的react js前端,但数据已成功发送到我的后端.当我发送普通的键值对而没有数组时,它也可以正常工作.
I send a number of files and some other data via redux and axios to my backend. However, when I do so, I get the following error message Unhandled Rejection (TypeError): state.story is not iterable
. Although the error occurs in my react js fronted, the data is successfully sent to my backend. When i send normal key vlaue pairs and no array it also works fine.
我现在想知道如何使 state.story 可迭代?或者更一般地如何解决这个问题?
I now wonder how i can make state.story iterable? Or more general how to approach that issue?
// creating the form data
onClickUpload (e){
let files = this.state.image;
let formData = new FormData();
formData.append('title', "Some_Title")
for (var i = 0; i < files.length; i++) {
formData.append(`story_media[${i}]isTitlePicture`, files[i].isTitlePicture)
formData.append(`story_files[${i}]files`, files[i].file)
}
this.props.addStory(formData);
}
// ADD Story Action
export const addStory = formDataStory => (dispatch, getState) =>
new Promise((resolve, reject) => {
axios.post(apiBase +"/story/createupdatedestroy/", formDataStory, tokenConfig(getState) )
.then(res => {
dispatch(createMessage({ addStory: "Story Added" }));
dispatch({
type: ADD_STORY,
payload: res.data
});
resolve(res);
})
.catch(err => {
reject(err);
dispatch(returnErrors(err.response.data, err.response.status))
}
);
// Add STory Reducer
const initialState = {
story: [],
isFetching: "idle"
};
export default function (state = initialState, action) {
switch (action.type) {
case GET_STORY_REQUEST:
return {
...state,
isFetching: "loading"
};
case GET_STORY_SUCCESS:
return {
...state,
story: action.payload,
isFetching: "success"
};
case GET_STORY_FAILURE:
return {
isFetching: "failure"
};
case GET_SINGLE_STORY:
return {
...state,
story: state.story.filter(story => story.id !== action.payload)
};
case DELETE_STORY:
return {
...state,
story: state.story.filter(story => story.id !== action.payload)
};
case EDIT_STORY:
return {
...state,
story: state.story.filter(story => story.id !== action.payload)
};
case ADD_STORY:
return {
...state,
story: [...state.story, action.payload]
};
default:
return state;
}
}
推荐答案
Issue
您的减速器案例之一没有正确复制状态对象.它忽略了将当前状态复制到新状态对象中.
Issue
One of your reducer cases is not copying the state object correctly. It neglects to copy current state into the new state object.
case GET_STORY_FAILURE:
return {
isFetching: "failure"
};
解决方案
将现有状态复制到新状态对象中.
Solution
Copy existing state into the new state object.
case GET_STORY_FAILURE:
return {
...state,
isFetching: "failure"
};
这篇关于如何使状态可迭代并解决“未处理的拒绝(TypeError):state.story 不可迭代"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!