【发布时间】:2020-02-12 16:34:42
【问题描述】:
我有一个使用 React、Redux (Redux Thunk) 的应用程序。在将获取帖子插入表后,我在更新减速器中的状态时遇到问题。 我正在尝试调度一个动作并将一些信息从动作传递给减速器,但无法这样做。我特别试图将获取响应传递给调度。我的调度中有一个名为 res 的键。我将它设置为一个数据值,但我相信这个数据值是未定义的。
export function insertSearchTerm(searchTerm) {
console.log('C')
return (dispatch) => {
fetch('http://localhost:3001/api/v1/searches?searchterm='+ searchTerm, {
headers: {
'Content-Type':'application/json', //headers - tells y9ou that it is json
},
method:'POST',
body: JSON.stringify(searchTerm) //stringifies searchTerm
}).then(res => console.log('Inside insertSearch Term resp', res.json()))
.then(data => {
dispatch({
type:'INSERT_SEARCH_TERM',
searchTerm: searchTerm,
res : data
})
}
)
}
console.log('E')
}
export default function allSearchTermsReducer(state = {allSearchTerms: []}, action) {
switch (action.type) {
case 'ALL_SEARCHES':
console.log("Allsearch reducer",action.payload);
return {...state, allSearchTerms: action.payload}
case 'INSERT_SEARCH_TERM':
console.log('insert search term action', action)
return {
...state,
allSearchTerms: [...state.allSearchTerms, action.id, action.searchTerm, action.created_at] }
default:
return state
}
};
【问题讨论】: