rn: 0.42
- i tried use new navigation (that released) + redux , unable map initial state of redux props, in screen store passed.
- i followed this: https://reactnavigation.org/docs/guides/redux
- i have written custom reducer.
export const types = { ... } export const actioncreators = { authenticate: () => async (dispatch, getstate) => { ... } } const initialstate = { auth: { ... } } export const reducer = (state = initialstate, action) => { const {auth} = state const {type, payload, error} = action switch (type) { ... } return state }
- in index.ios.js have combined own custom reducer
import { addnavigationhelpers } 'react-navigation'; import * 'appreducer'; const appnavigator = stacknavigator({ home: { screen: mytabnavigator }, }); const navreducer = (state, action) => { const newstate = appnavigator.router.getstateforaction(action, state); return (newstate ? newstate : state) }; const appreducer = combinereducers({ nav: navreducer, app: appreducer }); @connect(state => ({ nav: state.nav, })) class appwithnavigationstate extends react.component { render() { return ( <appnavigator navigation={addnavigationhelpers({ dispatch: this.props.dispatch, state: this.props.nav, })} /> ); } } const store = createstore(appreducer); class app extends react.component { render() { return ( <provider store={store}> <appwithnavigationstate /> </provider> ); } }
- inside home.js, 'mapstatetoprops' not work.
import react, { component } 'react' import { view, text, stylesheet } 'react-native' import { connect } 'react-redux' import { actioncreators } './appredux' const mapstatetoprops = (state) => ({ //this problem: here 'state' has no 'auth' object attached auth: state.auth }) class home extends component { componentwillmount() { const {dispatch} = this.props //dispatch works dispatch(actioncreators.authenticate('testid', 'testtoken')) } render() { const {auth} = this.props return ( <view style={styles.container}> <text> welcome {auth['name']} </text> </view> ) } } const styles = stylesheet.create({ container: { flex: 1, } }) export default connect(mapstatetoprops)(home)
- note, dispatch function available fire 'state' not have reducer 'initialstate' attached it.
please let me know correct way attach reducer initialstate various screens in new rn navigation.
i got doing wrong, in index.ios.js change import * 'appreducer';
import {reducer} 'appreducer';
current combined reducer function
const appreducer = combinereducers({ nav: navreducer, app: reducer });
then in home.js mapstatetoprops should like
const mapstatetoprops = (state) => ({ //this problem: here 'state' has no 'auth' object attached authstate: state.app //remember store contains reducers state had passed in combinereducer function })
now use in component
this.props.authstate.auth //remember had wrapped auth object within initialstate object
Comments
Post a Comment