【问题标题】:How do I update Redux store with POST response?如何使用 POST 响应更新 Redux 存储?
【发布时间】: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
  }
};

【问题讨论】:

    标签: reactjs redux


    【解决方案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')
       }
    

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 2021-10-10
      • 1970-01-01
      • 2020-12-08
      • 2020-10-15
      • 2017-07-10
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多