无法读取 Redux 中未定义的属性“类型”
2021-01-03
783
我正在编写 React 函数组件,该组件应该从服务器获取一些数据。我使用 redux,但出现错误“无法读取未定义的属性‘type’”
请帮我找出我的错误
这是我的 React 组件 Products.js。我认为导出部分可能有错误。父组件 Products.js(App.js)也包装在 Provider 上
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchProducts } from '../actions/productActions';
import { productsReducer } from '../reducers/productReducers'
function Products({ store, products, cartItems, setCartItems }) {
useEffect(() => {
store.dispatch(productsReducer())
})
const [product, setProduct] = useState(null);
return (
<div>
{
!products
? (<div>Loading...</div>)
:
(<ul className="products">
{products.map(product => (
<li key={product._id}>
<div className="product">
<a href={"#" + product._id}>
<img src={product.image} alt={product.title} />
<p>{product.title}</p>
</a>
<div className="product-price">
<div>${product.price}</div>
<button>Add To Cart</button>
</div>
</div>
</li>
))}
</ul>)
}
</div >
)
}
export default connect((state) => ({ products: state.products.items }), {
fetchProducts,
})(Products);
这是我的 store.js
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { productsReducer } from './reducers/productReducers';
const initialState = {};
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
combineReducers({
products: productsReducer,
}),
initialState,
composeEnhancer(applyMiddleware(thunk))
)
export default store;
我的 Reducer,我在此文件中收到错误(无法读取未定义的属性“type”),也许,我犯了一个传输错误“action”
import { FETCH_PRODUCTS } from "../types";
export const productsReducer = (state = {}, action) => {
switch (action.type) {
case FETCH_PRODUCTS:
console.log('it work!')
return { items: action.payload };
default:
return state;
}
};
我的 Action
import { FETCH_PRODUCTS } from "../types";
export const fetchProducts = () => async (dispatch) => {
const res = await fetch("/api/products");
const data = await res.json();
console.log(data);
dispatch({
type: FETCH_PRODUCTS,
payload: data,
});
};
和我的类型
export const FETCH_PRODUCTS = "FETCH_PRODUCTS"
这是关于 redux 的学习项目,但原始老师在类组件上编写了代码。原始代码 这里 和 这里
如果我像在源代码上那样编写类组件,则一切都正常工作,所以我认为这是一个错误的原因
1个回答
dispatch
函数需要 redux 操作作为参数,而不是 Reducer。在您的案例中:
import { fetchProducts } from '../actions/productActions';
function Products({ store, products, cartItems, setCartItems }) {
useEffect(() => {
store.dispatch(fetchProducts());
})
...
}
oozywaters
2021-01-03