我试图解决这个问题 2 天,但直到现在我还没有得到解决方案,任何人都可以帮助我, 类别在控制台中成功渲染,redux 正常使用数据但未在屏幕上渲染
类别屏幕
const category = useSelector(state => state.category);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getCategory());
}, [dispatch]);
const renderCategories = (categories) => {
let myCategories = [];
for (let category of categories) {
myCategories.push(
<li key={category.name}>
{category.name}
{/* {category.children.length > 0 ? (<ul>{renderCategories(category.children)}</ul>) : null} */}
</li>
);
}
return myCategories;
}
这部分的返回(问题出在这里(Cannot read property 'categories' of undefined)
<Col md={12}>
<ul>
{renderCategories(category.categories)}
</ul>
</Col>
减速器
const initState = {
categories: [],
loading: false,
error: null
};
export const getCategoryReducer = (state = initState, action) => {
switch (action.type) {
case GET_CATEGORY_SUCCESS:
return { ...state, categories: action.payload.categories };
default:
return state;
}
};
获取操作
export const getCategory = () => {
return async dispatch => {
dispatch({ type: GET_CATEGORY_REQUEST })
const res = await axios.get(`api/category/getcategory`);
console.log(res);
if (res.status === 200) {
const { categories } = res.data;
dispatch({ type: GET_CATEGORY_SUCCESS, payload: { categories: categories } })
} else {
dispatch({ type: GET_CATEGORY_FAIL, payload: { error: res.data.error } })
}
}
}
商店
import { createStore, compose, applyMiddleware, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { getCategoryReducer } from './reducers/categoryReducers';
import {
userDeleteReducer,
userDetailsReducer,
userListReducer,
userRegisterReducer,
userSigninReducer,
userUpdeteProfileReducer,
userUpdeteReducer,
} from './reducers/userReducers';
const initialState = {
userSignin: {
userInfo: localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: null,
},
};
const reducer = combineReducers({
userSignin: userSigninReducer,
userRegister: userRegisterReducer,
userDetails: userDetailsReducer,
userUpdateProfile: userUpdeteProfileReducer,
userUpdate: userUpdeteReducer,
userList: userListReducer,
userDelete: userDeleteReducer,
getCategory: getCategoryReducer,
});
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducer,
initialState,
composeEnhancer(applyMiddleware(thunk))
);
export default store;
后端路由器
categoryRouter.get(
'/getcategory',
(req, res) => {
Category.find({}).exec((error, categories) => {
if (error) return res.status(400).json({ error });
if (categories) {
res.status(200).json({ categories });
}
});
});
export default categoryRouter;
类别模型
import mongoose from 'mongoose';
const categorySchema = new mongoose.Schema(
{
name: { type: String, required: true, trim: true },
slug: { type: String, required: true, unique: true },
parentId: { type: String }
}, { timestamps: true }
);
const Category = mongoose.model('Category', categorySchema);
export default Category;
答案 0 :(得分:0)
category
可以是未定义的,直到状态已满。所以你可以这样试试:
{renderCategories(category?.categories)}
答案 1 :(得分:0)
问题来了:
const reducer = combineReducers({
userSignin: userSigninReducer,
userRegister: userRegisterReducer,
userDetails: userDetailsReducer,
userUpdateProfile: userUpdeteProfileReducer,
userUpdate: userUpdeteReducer,
userList: userListReducer,
userDelete: userDeleteReducer,
getCategory: getCategoryReducer,
});
您的组合减速器创建了一个 getCategory
,而不是一个 category
。为了使用 useSelector
正确提取它,您应该更改它:
const category = useSelector(state => state.getCategory);
或在您的 combineReducers 重命名:
const reducer = combineReducers({
userSignin: userSigninReducer,
userRegister: userRegisterReducer,
userDetails: userDetailsReducer,
userUpdateProfile: userUpdeteProfileReducer,
userUpdate: userUpdeteReducer,
userList: userListReducer,
userDelete: userDeleteReducer,
category: getCategoryReducer,
});