我正在编写反应功能组件,它应该从服务器获取一些数据。我正在使用 redux,但出现错误“无法读取未定义的属性‘类型’”
请帮我找出我的错误
这是我的 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;
我的减速器,我在这个文件中遇到错误(无法读取未定义的属性“类型”),也许,我犯了一个传输错误“动作”
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;
}
};
我的操作
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 的学习项目,但在原始教师编写的 class 组件上的代码。原始代码 here 和 here
如果我像在源代码上一样编写类组件,一切正常,所以我认为这是错误的原因
答案 0 :(得分:1)
dispatch
函数期望 redux action 作为参数,而不是 reducer。在你的情况下:
import { fetchProducts } from '../actions/productActions';
function Products({ store, products, cartItems, setCartItems }) {
useEffect(() => {
store.dispatch(fetchProducts());
})
...
}