因此,我遵循这个教程,我挣扎与以下步骤。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
}
}
2条答案
按热度按时间jecbmhm31#
你应该一致地命名状态。状态最初被命名为
products
,但是所有的大小写归约器都用product
来替换它。不要忘记总是将前一个状态对象浅复制到下一个状态对象中。nnt7mjpx2#
在
const {error, loading, products} = productList
这一行中,您尝试访问的产品在您的州中不存在,您的州返回的内容与您的reducerreturn {loading:true, product:[]}
中的内容类似。将该行const {error, loading, products} = productList
更改为const {error, loading, product} = productList
。products变为product