如何使用POST响应更新Redux存储?

时间:2019-10-16 00:11:41

标签: reactjs redux

我有一个使用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
  }
};

1 个答案:

答案 0 :(得分:1)

在动作创建者中,对于第一个.then块,您将返回console.log()而不是数据本身。因此,在进行中的.then块中没有要分发的数据。应该更新为:

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 => res.json())
        .then(data => {
            dispatch({
               type:'INSERT_SEARCH_TERM',
               searchTerm: searchTerm,
               res : data
            })
          }
        )
      }
     console.log('E')
   }