簡體   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