因此,我遵循本教程,并在以下步骤中苦苦挣扎。Redux被引入,但它不起作用。我在谷歌上搜索了我在开发者工具中发现的错误,但我仍然无法通过尝试许多建议的解决方案来修复错误。错误在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
}
}
您应该一致地命名状态。该状态最初命名为products
,但所有大小写减速器都将其替换为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;
}
}