gpt4 book ai didi

reactjs - 在 Redux + React Native + react-navigator 中传递参数

转载 作者:行者123 更新时间:2023-12-01 16:15:35 26 4
gpt4 key购买 nike

我正在尝试将参数从 MenuScreen.js 传递到 ProfileScreen.js。我是 React Native 和 Redux 的新手。使用 react-navigation 进行导航,我可以使用按钮推送到新屏幕。

使用

Button onPress={() => dispatch(NavigationActions.navigate({ routeName: 'Profile', params: { user: 'baz' } }))} title="Profile" />

我可以传递参数,但我不知道如何在配置文件屏幕上访问它。

使用

this.props.navigation.state.params

ProfileScreen.js 中给出了一个错误

this.props.navigation

未定义。

下面是代码,

MainScreen.js

const MainScreen = ({ dispatch }) => {

return (
<View>

<Button
onPress={() =>
dispatch(NavigationActions.navigate({ routeName: 'Profile', params: { user: 'baz' } }))}
title="Profile"
/>
</View>
);
};

MainScreen.propTypes = {
dispatch: PropTypes.func.isRequired,
};

MainScreen.navigationOptions = {
title: 'Main',
};

const mapStateToProps = state => ({

});

export default connect(mapStateToProps)(MainScreen);

ProfileScreen.js

const params  = this.props.navigation.state.params;

const ProfileScreen = () => (
<View style={styles.container}>
<Text style={styles.welcome}>
{params}
</Text>
</View>
);

ProfileScreen.navigationOptions = {
title: 'Profile',
};

export default ProfileScreen;

index.reducer.js

import { AppNavigator } from '../navigators/AppNavigator';

const initialNavState = AppNavigator.router.getStateForAction(
AppNavigator.router.getActionForPathAndParams('Main')
);

function nav(state = initialNavState, action) {
let nextState;
switch (action.type) {
default:
nextState = AppNavigator.router.getStateForAction(action, state);
break;
}
return nextState || state;
}

const AppReducer = combineReducers({
nav,
});

export default AppReducer;

AppNavigator.js

import MainScreen from '../components/MainScreen';
import MainScreen from '../components/MainScreen';
import ProfileScreen from '../components/ProfileScreen';

export const AppNavigator = StackNavigator({
Main: { screen: MainScreen },
Profile: { screen: ProfileScreen },
});

const AppWithNavigationState = ({ dispatch, nav }) => (
<AppNavigator navigation={addNavigationHelpers({ dispatch, state:
nav })} />
);

AppWithNavigationState.propTypes = {
dispatch: PropTypes.func.isRequired,
nav: PropTypes.object.isRequired,
};

const mapStateToProps = state => ({
nav: state.nav,
});

export default connect(mapStateToProps)(AppWithNavigationState);

index.ios.js

class NavChecks extends React.Component {
store = createStore(AppReducer);

render() {
return (
<Provider store={this.store}>
<AppWithNavigationState />
</Provider>
);
}
}

AppRegistry.registerComponent('NavChecks', () => NavChecks);

export default NavChecks;

最佳答案

尝试将 Prop 传递给 ProfileScreen。在我看来,使用 react-native-router-flux 进行导航更加灵活,我认为您可以在导航到其他页面时将参数作为 Prop 传递

关于reactjs - 在 Redux + React Native + react-navigator 中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46038749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com