未捕获的类型错误:无法读取未定义的属性(读取‘map’)React
2022-08-23
2530
因此,我正在按照本教程操作,但接下来的步骤却让我很为难。Redux 被引入了,但它不起作用。我在 Google 上搜索了我在开发者工具中发现的错误,尝试了许多建议的解决方案,但仍然无法修复该错误。错误位于 HomeScreen 的第 25 行 (products.map) 我的代码:
HomeScreen.js:
import React, {useState, useEffect} from 'react'
import {Row, Col} from 'react-bootstrap'
import Product from '../components/Product'
import { useDispatch, useSelector} from 'react-redux'
import {listProducts} from '../actions/productActions'
function HomeScreen() {
const dispatch = useDispatch()
const productList = useSelector(state => state.productList)
const {error, loading, products} = productList
useEffect(() =>{
dispatch(listProducts())
},[dispatch])
return (
<div>
<h1>Latest Products</h1>
{loading ? <h2>Loading..</h2>
: error ? <h3>{error}</h3>
:
<Row>
{products.map(product => (
<Col key={product._id} sm={8} md={6} lg={4} xl={2}>
<Product product={product} />
</Col>
))}
</Row>
}
</div>
)
}
store.js:
import { legacy_createStore as createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import {productListReducer} from './reducers/productReducers'
const reducer = combineReducers({
productList: productListReducer,
})
const initialState = {}
const middleware = [thunk]
const store = createStore(reducer, initialState,
composeWithDevTools(applyMiddleware(...middleware)))
export default store
productActions.js:
import axios from 'axios'
import {PRODUCT_LIST_REQUEST,PRODUCT_LIST_SUCCESS,PRODUCT_LIST_FAIL} from '../constants/productConstants'
export const listProducts = () => async(dispatch) => {
try {
dispatch({type: PRODUCT_LIST_REQUEST})
const {data} = await axios.get('/api/products/')
dispatch({
type: PRODUCT_LIST_SUCCESS,
payload: data
})
} catch (error) {
dispatch({
type: PRODUCT_LIST_FAIL,
payload: error.response && error.response.data.message
? error.response.data.message
: error.message,
})
}
}
productReducers.js
import {
PRODUCT_LIST_REQUEST,
PRODUCT_LIST_SUCCESS,
PRODUCT_LIST_FAIL
} from '../constants/productConstants'
export const productListReducer = (state={products:[]},action) => {
switch(action.type){
case PRODUCT_LIST_REQUEST:
return {loading:true, product:[]}
case PRODUCT_LIST_SUCCESS:
return {loading:false, product:action.payload}
case PRODUCT_LIST_FAIL:
return {loading:false, error: action.payload}
default:
return state
}
}
1个回答
您应该一致地命名状态。状态最初名为
products
,但所有 case Reducer 都将其替换为
product
。不要忘记始终将上一个状态对象浅复制到下一个状态对象中。
export const productListReducer = (state={ products: [] }, action) => {
switch(action.type) {
case PRODUCT_LIST_REQUEST:
return {
...state,
loading: true,
products: [],
};
case PRODUCT_LIST_SUCCESS:
return {
...state,
loading: false,
products: action.payload,
error: null,
};
case PRODUCT_LIST_FAIL:
return {
...state,
loading: false,
error: action.payload,
};
default:
return state;
}
}
Drew Reese
2022-08-23