React Native集成Redux时mapStateToProps传递props为空对象问题
问题分析与修复方案
我一眼就发现两个核心问题导致你的Decider组件接收到的props是空对象,咱们逐个解决:
1. 未正确使用connect()返回的已连接组件
你在代码里调用了connect(mapStateToProps)(Decider),但没有把这个函数返回的、已经和Redux store绑定的组件赋值给原来的Decider变量。这就导致你的App组件里渲染的还是那个未关联Redux的原始Decider类,自然拿不到store里的状态数据。
2. mapStateToProps的状态取值路径错误
你的rootReducer是用combineReducers把auth和viewControl两个reducer组合起来的,所以Redux store的根状态结构是这样的:
{ auth: /* auth reducer管理的状态 */, viewControl: /* viewControl reducer管理的布尔状态 */ }
你之前写的state.showIntro完全找不到对应的字段——根状态里根本没有showIntro这个属性,应该取state.viewControl才对。
修正后的App.js代码
import Intro from './pages/Intro'; import Content from './pages/Content'; const store = createStore(rootReducer) export default class App extends Component { render() { return ( <Provider store={store}> <Decider /> </Provider> ) } } class Decider extends Component { render() { return this.props.showIntro ? <Intro /> : <Content /> } } // 关键修正1:把connect返回的已连接组件赋值给Decider const mapStateToProps = state => { // 关键修正2:正确获取viewControl reducer管理的状态 return { showIntro: state.viewControl } } Decider = connect(mapStateToProps)(Decider)
额外优化建议(可选)
为了避免action type字符串拼写错误,建议把action type定义成常量,比如在actions/index.js里:
export const ON_INTRO_COMPLETION = 'ON_INTRO_COMPLETION'; export const onIntroCompletion = bool => { return { type: ON_INTRO_COMPLETION, payload: false } }
然后在reducer里也引用这个常量:
import { ON_INTRO_COMPLETION } from '../actions'; const viewControl = (state = true, action) => { switch (action.type) { case ON_INTRO_COMPLETION: return action.payload default: return state; } };
内容的提问来源于stack exchange,提问作者WillKre
相关产品推荐
相关产品推荐

