繁体   English   中英

如何在页面之间/跨页面传递/发送状态?

[英]How to pass/send state between/across pages?

我已经在我的应用程序中完成了一些代码,但似乎可以通过全局变量进行传递。

我在Auth.js设置了一个全局变量。

export const _values = { 
  username: ''
};

SignUp.js获取用户名值。

import { onSignIn, onSignUp, _values } from "../Auth";

export default ({ navigation }) => (
  <View style={{ paddingVertical: 20 }}>
    <Card title="SIGN UP">
      <FormLabel>Email</FormLabel>
      <FormInput 
        placeholder="Email address..."
        onChangeText={(val) => _values.username = val}
      />

     ...

    </Card>
  </View>
);

我想跨页面使用state技术传递用户名值( Home.js & Profile.js )。

参考: https : //github.com/datomnurdin/auth-reactnative

您可以将redux用于状态管理。\\

https://redux.js.org/

或者,如果您的应用程序不太复杂,则可以转到Context Api

https://medium.com/@505aaron/a-practical-react-native-problem-solved-with-the-context-api-eecaf2e05202

更新:这是context api的演示。

假设您必须更改一个用户,并且希望每个组件中都有该用户。 每当用户更改时,都需要更新的用户。 因此,您需要在每个组件中访问该用户,并且也能够对其进行更改。

首先创建一个用户上下文,让我们创建一个名为UserContext.js的文件:

import React from 'react';
const Context = React.createContext('username');
export class UserStore extends React.Component {
    state = {
        language: 'username'
    }
    onUserChange = username => this.setState({ username });
    render() {
        return (
            <Context.Provider value={{ ...this.state, onUserChange: this.onUserChange }}>
                {this.props.children}
            </Context.Provider>
        );
    }
}
export default Context;

现在您有了一个userContext,其初始值为username = 'username'

而且无论何时您要访问或更改它,您都只需要使用使用者。

import React from 'react';
import Context from '../contexts/UserContext';

class UserSelector extends React.Component {
    renderContent = (store) => {    
        return (
            <View>
                <Text>Choose a User</Text>
                 <Button 
                  title='Change User'
                  onPress ={() =>store.onUserChange('mark')}
                  />
            </View>
        );
    }
    render() {
        return (
            <Context.Consumer>
                {this.renderContent}
            </Context.Consumer>
        );
    }
}
export default UserSelector;

暂无
暂无

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

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