redux React减速器获取有效负载:未定义

1tuwyuhd  于 2023-03-02  发布在  React
关注(0)|答案(2)|浏览(203)

我试着从Googlesheets中获取一些数据并将其发送到Reduce。当我从工作表中获取数据时,我会在控制台中检查它,当我将其发送到Reduce并在控制台中检查它时,它是未定义的。
减速器:

const defaultState = {
  data: [],
}

const GET_DATA_FROM_GOOGLE = "GET_DATA_FROM_GOOGLE"

export const googleDataReducer = (state = defaultState, action) => {
  switch (action.type) {
    case "GET_DATA_FROM_GOOGLE":
      console.log('1 reducer')
      console.log(action) // there are payload:undefined 
      console.log('2 reducer')
      return {
        ...state,
        data: action.payload
      }    

    default:
      return state
  }
}

export const getDataFromGoogleAction = (payload) => ({
  type: GET_DATA_FROM_GOOGLE,
  payload
})

我在哪里从googlesheet获取数据:

import { getDataFromGoogleAction } from "../store/googleDataReducer.js"

export const fetchData = () => {
  return function(dispatch) {
    let onlySmr fetch('https://script.google.com/macros/s/AKfycbyfcEvLSna_NbO-FDPSuo_efg7tK2uVugGDGTBqpQ1mrFvNPnqEGUFbPLgD-buhj4kT/exec') 
      .then((response) => response.json())
      .then((response) => onlySmr = response['smr']) // there are normal data 
      .then((onlySmr) => console.log(onlySmr))
      .then((onlySmr) => dispatch(getDataFromGoogleAction(onlySmr))) 
  }
}
tmb3ates

tmb3ates1#

问题出在fetchData函数中。Promise链在返回定义的响应值时中断,特别是在您尝试记录该值的.then-able中。console.log是void返回。如果要在中途记录值,则仍需要在链中返回该值。

错误代码

export const fetchData = () => {
  return function(dispatch) {
    let onlySmr fetch('https://script.google.com/macros/s/..../exec') 
      .then((response) => response.json())
      .then((response) => onlySmr = response['smr']) 
      .then((onlySmr) => console.log(onlySmr))     // <-- onlySmr not returned
      .then((onlySmr) => {
        dispatch(getDataFromGoogleAction(onlySmr)) // <-- onlySmr undefined
      });
  }
}

良好代码

我建议在调度getDataFromGoogleAction操作之前,在最后一个.then-able中记录onlySmr

export const fetchData = () => dispatch => {
  fetch('https://script.google.com/macros/s/..../exec') 
    .then((response) => response.json())
    .then((data) => {
      const onlySmr = data['smr'];
      console.log(onlySmr);                       // <-- log onlySmr value
      dispatch(getDataFromGoogleAction(onlySmr)); // <-- onlySmr defined
    });
}
mspsb9vt

mspsb9vt2#

console.log()的返回值始终为undefined。因此,onlySmr在最后一个.then链中为undefined。因此,payloadundefined
如果你想保留当前代码,你必须在console.log()之后返回onlySmr。但是,使用这么多then是不必要的。你可以这样做:

export const fetchData = () => {
  return function(dispatch) {
    let onlySmr fetch('https://script.google.com/macros/s/AKfycbyfcEvLSna_NbO-FDPSuo_efg7tK2uVugGDGTBqpQ1mrFvNPnqEGUFbPLgD-buhj4kT/exec')
      .then((response) => {
        const onlySmr = response.json()["smr"]
        console.log(onlySmr)
        dispatch(getDataFromGoogleAction(onlySmr))
      })
  }
}

参考:

https://developer.mozilla.org/en-US/docs/Web/API/Console/log

相关问题