Expo开发React Native应用接入Redux提示找不到store如何解决?
问题原因及修复方案
核心错误原因
你修改代码后出现错误的核心原因是根组件注册逻辑完全错误:
你在App.js末尾执行了export default registerRootComponent(AppRoot),相当于直接告诉Expo把连接了Redux的App组件作为整个应用的根节点启动,你写的包含<Provider store={store}>的AppProvider组件根本没有被挂载到渲染树中,connect包装后的App自然找不到外层的Redux store。
除此之外你还存在3处代码错误:
reducers.js拼写错误:导入的方法名是combineReducers,导出时写成了combinedReducersApp组件内属性调用错误:mapStateToProps返回的状态会直接挂载到组件props下,不需要再加一层state,且组件内部没有初始化this.state.token- 两个reducer的action type重复,会导致任意一个action触发时两个状态同时被修改
修复步骤
1. 修正根组件注册逻辑
- 删掉
App.js末尾的export default registerRootComponent(AppRoot);,替换为普通导出:
const connector = connect(mapStateToProps, mapDispatchToProps) export default connector(App);
- 在
index.js末尾添加根组件注册逻辑:
export default registerRootComponent(AppProvider);
2. 修正reducers拼写错误
修改reducers.js最后一行的方法名,和导入名保持一致:
export default combineReducers({ NCServer: NCServerReducer, token: tokenReducer });
3. 修正App组件内的属性调用
- 把constructor中的
this.props.state.setToken(token)改为this.props.setToken(token) - 把render判断条件中的
this.state.token === null改为this.props.token === null
额外逻辑优化(必改,否则状态会混乱)
修改action和reducer的type值,避免重复:
// actions.js export const setNCServer = NCServer => ({ type: 'SET_NC_SERVER', payload: NCServer, }); export const setToken = token => ({ type: 'SET_TOKEN', payload: token, });
对应修改reducer的判断条件:
// reducers.js const tokenReducer = (state = null, action) => { switch (action.type) { case 'SET_TOKEN': return action.payload; default: return state } }; const NCServerReducer = (state = null, action) => { switch (action.type) { case 'SET_NC_SERVER': return action.payload; default: return state } };
内容的提问来源于stack exchange,提问作者StCyr
相关产品推荐
相关产品推荐

