简体   繁体   English

如何使用 React Redux 存储和导航?

[英]How to store and navigate with React Redux?

I'm new to react-redux and react-navigation.我是 react-redux 和 react-navigation 的新手。 I'm trying to build a simple app with a TextInput in the MainScreen that the user types his username and when he press "Login" that username will be saved up in the redux store and the navigation will navigate automatically to the "HomeScreen".我正在尝试在 MainScreen 中构建一个带有 TextInput 的简单应用程序,用户输入他的用户名,当他按下“登录”时,该用户名将保存在 redux 商店中,导航将自动导航到“主屏幕”。

App.js:应用程序.js:

const initialState = { username: "" };
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "STORE_USERNAME":
      return { username: state.username };
    default:
      return state;
  }
};

const store = createStore(reducer);

MainScreen.jsx:主屏幕.jsx:

const mapStateToProps = state => {
  return {
    username: state.username
  };
};
const mapDispatchToProps = dispatch => {
  return {
    storeUsername: () => {
      dispatch({ type: "STORE_USERNAME" });
    }
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(Main);

What should I change or add?我应该更改或添加什么?

First you need to create an appNavigator from react-navigation like this :首先,您需要像这样从 react-navigation 创建一个 appNavigator:

import {createAppContainer, createSwitchNavigator} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
const AppStack = createStackNavigator({
    HomeScreen: {
      screen: Home,
    },
    Login: {
      screen: Login,
    }});


const navigation = createAppContainer(AppStack);

And suppose what you are doing by storing username in redux state is correct, just now you need to navigate it.并且假设您通过将用户名存储在 redux 状态中所做的操作是正确的,现在您需要导航它。

SO suppose in Login.js所以假设在 Login.js

onButtonPress = () => {
this.props.storeUsername();
this.props.navigation.navigate('Home');// here you are redirecting to the main page after username has been stored.
}

render(){

return(
// your other code
<Button onPress={this.onButtonPress} title="submit username">
)

}

const mapStateToProps = state => {
  return {
    username: state.username
  };
};
const mapDispatchToProps = dispatch => {
  return {
    storeUsername: () => {
      dispatch({ type: "STORE_USERNAME" });
    }
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(Login);

Hope it helps.希望能帮助到你。 feel free for doubts随意怀疑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM