我正在尝试构建一个应用程序,该应用程序有两个或更多个reducer“回答”我的storeState中的一个对象.
例:
storeState { app: {...},comments: [ ...two or more states inside one... ] }
我已经尝试了以下使用不起作用的combineReducers,我的注释状态变成了一个空对象.
import { combineReducers } from 'redux'; import commentFacebookReducer from './twitch'; import commentYoutubeReducer from './reddit'; import appReducer from './app'; const rootReducer = combineReducers({ comments: [commentFacebookReducer,commentYoutubeReducer],app: appReducer }); export default rootReducer;
我已经尝试将我的评论缩减器组合在一起,然后将它们组合在rootReducer中:
import { combineReducers } from 'redux'; import commentFacebookReducer from './twitch'; import commentYoutubeReducer from './reddit'; import appReducer from './app'; const commentReducers = combineReducers({ commentFacebookReducer,commentYoutubeReducer }); const rootReducer = combineReducers({ comments: commentReducers,app: appReducer }); export default rootReducer;
但它给了我一个像以下那样的storeState.但我需要一个注释数组的状态,我不能处理这些减少名称(如commentFacebookReducer或commentYoutubeReducer),因为我会有数千个这样的减速器.
storeState { app: {...},comments: { commentFacebookReducer: {...},commentYoutubeReducer: {...} } }
我不认为你可以通过使用combineReducer来做到这一点.因为combineReducer需要一个对象,该对象的每个属性都应该是
一个功能.然后该对象中的每个函数在redux状态树中创建一个单独的属性,该属性的值是该函数返回的值(当调度任何操作时).
一个功能.然后该对象中的每个函数在redux状态树中创建一个单独的属性,该属性的值是该函数返回的值(当调度任何操作时).
此外,您无法在其他reducer中访问一个reducer的状态,因为redux仅将该特定reducer的状态传递给该函数.这意味着你无法在commentYoutubeReducer中获取/更改commentFacebookReducer的状态.
我现在能想到的唯一更好的解决方案是在使用它们时将它们组合在一起(最有可能在mapStateToProps中).你保持你的减速器就像你这样做:
const commentReducers = combineReducers({ commentFacebookReducer,app: appReducer });
现在我们所有的评论都在一个对象中,即(state.comments).现在在mapStateToProp中你可以做这样的事情,将它们组合在一个对象中::
const mapStateToProps = state => { return { comments: Object.keys(state.comments).reduce((d,k) => {return d.concat(a[k])},[] ) }; };
现在在组件中,您可以使用this.props.comments将它们作为单个数组进行访问
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。