React Reducer接收Payload为undefined问题排查求助
问题:Google Sheets数据获取后Reducer中payload为undefined
我尝试从Google Sheets获取数据并发送至React Reducer。获取数据时控制台能看到正常数据,但发送到Reducer后,控制台显示payload为undefined。
Reducer代码
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) // 此处payload为undefined console.log('2 reducer') return { ...state, data: action.payload } default: return state } } export const getDataFromGoogleAction = (payload) => ({ type: GET_DATA_FROM_GOOGLE, payload })
数据获取代码(从Google Sheets拉取数据)
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']) // 此处能看到正常数据 .then((onlySmr) => console.log(onlySmr)) .then((onlySmr) => dispatch(getDataFromGoogleAction(onlySmr))) } }
问题原因
Promise的then回调如果没有显式返回值,默认会返回undefined。你的代码里:
- 第二个
then仅给onlySmr赋值,无返回值,导致第三个then接收的onlySmr是undefined - 第三个
then仅执行console.log,同样无返回值,使得第四个then里的onlySmr也为undefined,最终传给getDataFromGoogleAction的参数就是undefined
修复方案
调整Promise链的返回逻辑,确保每个then都传递需要的值:
import { getDataFromGoogleAction } from "../store/googleDataReducer.js" export const fetchData = () => { return function(dispatch) { fetch('https://script.google.com/macros/s/AKfycbyfcEvLSna_NbO-FDPSuo_efg7tK2uVugGDGTBqpQ1mrFvNPnqEGUFbPLgD-buhj4kT/exec') .then((response) => response.json()) .then((response) => { const onlySmr = response['smr']; console.log(onlySmr); return onlySmr; // 返回数据给下一个then }) .then((onlySmr) => dispatch(getDataFromGoogleAction(onlySmr))) } }
也可以用async/await简化逻辑,让代码更直观:
import { getDataFromGoogleAction } from "../store/googleDataReducer.js" export const fetchData = () => { return async function(dispatch) { const response = await fetch('https://script.google.com/macros/s/AKfycbyfcEvLSna_NbO-FDPSuo_efg7tK2uVugGDGTBqpQ1mrFvNPnqEGUFbPLgD-buhj4kT/exec'); const data = await response.json(); const onlySmr = data['smr']; console.log(onlySmr); dispatch(getDataFromGoogleAction(onlySmr)); } }
内容的提问来源于stack exchange,提问作者Дмитрий Серебро
相关产品推荐
相关产品推荐

