gpt4 book ai didi

javascript - Redux 无法读取未定义的属性 'payload'

转载 作者:行者123 更新时间:2023-11-28 13:11:53 27 4
gpt4 key购买 nike

我正在使用 Redux 和 React 从 API 加载数据。尽管成功提取数据并将其应用到状态,但它会抛出错误:

Uncaught TypeError: Cannot read property 'payload' of undefined.

这发生在控制台中的 FETCH_PRODUCT_LISTINGS_PENDING 操作类型之后。

react 组件:

import React from 'react';
import { connect } from 'react-redux';
import store from '../../../store';

import * as ProductListingActions from '../actions/ProductListingActions';

@connect((store) => {
return {
productListing: store.productListing.products
}
})

export default class ProductListingContainer extends React.Component {
constructor(data) {
super();
this.props = data;
this.props.dispatch(ProductListingActions.fetchProductListings());
}
render() {
return <div></div>;
}
}

reducer :

import CookieHandler from '../../../modules/CookieHandler';
const cookieHandler = new CookieHandler;

export default function reducer(
state = {
products: [],
fetching: false,
fetched: false,
error: null
}, action) {

switch(action.type) {
case "FETCH_PRODUCT_LISTINGS_PENDING":
return {
...state,
fetching: true,
}
break;
case "FETCH_PRODUCT_LISTINGS_REJECTED":
return {
...state,
fetching: false,
error: action.payload
}
break;
case "FETCH_PRODUCT_LISTINGS_FULFILLED":
return {
...state,
fetching: false,
fetched: true,
products: action.payload.data.default
}
break;
}

return state;
}

操作:

import Config from '../../../Config.js';
import store from '../../../store.js';
import axios from 'axios';

export function fetchProductListings() {
store.dispatch({
type: "FETCH_PRODUCT_LISTINGS",
payload: axios.get(Config.getConfigAPIUrl() + '/cartel/products')
})

}

如有任何帮助,我们将不胜感激

最佳答案

您正在调度对调度的调用,而不是调度对象。

this.props.dispatch(ProductListingActions.fetchProductListings());

function fetchProductListings() {
store.dispatch({
type: "FETCH_PRODUCT_LISTINGS",
payload: axios.get(Config.getConfigAPIUrl() + '/cartel/products')
})
}

如果你内联这个:

this.props.dispatch(
store.dispatch({
type: "FETCH_PRODUCT_LISTINGS",
payload: axios.get(Config.getConfigAPIUrl() + '/cartel/products')
})
)

你的 Action 创建者不应该调用调度,它应该只返回一个 Action :

export function fetchProductListings() {
return {
type: "FETCH_PRODUCT_LISTINGS",
payload: axios.get(Config.getConfigAPIUrl() + '/cartel/products')
}
}

但请记住,axios.get 是异步的,因此 payload 将是 promise 。您可能需要考虑添加 redux-thunk 来处理 promise 的履行。

关于javascript - Redux 无法读取未定义的属性 'payload',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41784441/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com