2017-04-12 7 views
0

저는 작업중인 반응하는 기본 응용 프로그램이 있습니다. 지금은 두 가지 견해를 갖고 싶습니다. 로그인 페이지와 메인 페이지. 그것은 지금까지 다음과 같습니다React Native - 조건부로보기를 렌더링합니다.

index.ios.js

import React, { Component } from 'react'; 
import { 
    AppRegistry, 
    Dimensions, 
    StyleSheet, 
    Text, 
    TextInput, 
    Button, 
    TouchableHighlight, 
    View 
} from 'react-native'; 
import Scanner from './app/components/Scanner'; 
import Login from './app/components/Login'; 
import Store from './app/mobx/store'; 

export default class TestApp extends Component { 
    render() { 
    if (Store.loggedIn()){ 
     return <Scanner /> 
    } else { 
     return <Login store={Store} /> 
    } 
    } 
} 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    flexDirection: 'row', 
    backgroundColor: '#114DA0' 
    } 
}); 

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

응용 프로그램/구성 요소/Login.js

import React, { Component } from 'react'; 

import { 
    StyleSheet, 
    Text, 
    View, 
    TextInput, 
    ScrollView 
} from 'react-native'; 
import Container from './Container'; 
import Button from './Button'; 
import Label from './Label'; 
import {observer} from 'mobx-react/native'; 

@observer 
export default class Login extends Component { 
    constructor() { 
    super(); 
    this.state = { 
     email: '', 
     password: '', 
     isLoggingIn: false, 
     message: '' 
    } 
    this._userLogin = this._userLogin.bind(this); 
    } 
    _userLogin() { 
    console.log("loggin in...") 
    this.setState({isLoggingIn: true, message:''}); 
    var params = { 
     email: this.state.email, 
     password: this.state.password 
    }; 
    var formBody = []; 
    for (var property in params) { 
     var encodedKey = encodeURIComponent(property); 
     var encodedValue = encodeURIComponent(params[property]); 
     formBody.push(encodedKey + "=" + encodedValue); 
    } 
    formBody = formBody.join("&"); 
    fetch("http://example.com:8000/auth/mobile_login", { 
     method: "POST", 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded' 
     }, 
     body: formBody 
     }) 
     .then((response) => { 
     return response.json() 
     }) 
     .then((response) => { 
     if (response.error) { 
      this.setState({message: response.message}); 
     } else if (response.user) { 
      this.props.store.logIn(response.user); 
     } 
     }) 
     .then(() => { 
     this.setState({isLoggingIn: false}) 
     }) 
     .done(); 
    } 
    render() { 
    return (
     <ScrollView style={styles.scroll}> 
      <Container> 
      <Label text="Email" /> 
      <TextInput 
       style={styles.textInput} 
       onChangeText={(email) => this.setState({email})} 
      /> 
      </Container> 
      <Container> 
      <Label text="Password" /> 
      <TextInput 
       secureTextEntry={true} 
       style={styles.textInput} 
       onChangeText={(password) => this.setState({password})} 
      /> 
      </Container> 
      <Container> 
      {!!this.state.message && (
       <Text style={{fontSize: 14, color: 'red', padding: 5}}> 
       {this.state.message} 
       </Text> 
      )} 
      <Button 
       label="Sign In" 
       styles={{button: styles.primaryButton, label: styles.buttonWhiteText}} 
       onPress={this._userLogin} /> 
      </Container> 
     </ScrollView> 
    ); 
    } 
} 

const styles = StyleSheet.create({ 
    ... 
}); 

응용 프로그램/구성 요소/Scanner.js

import React, { Component } from 'react'; 
import { 
    AppRegistry, 
    Dimensions, 
    StyleSheet, 
    Text, 
    TouchableHighlight, 
    View 
} from 'react-native'; 
import Camera from 'react-native-camera'; 

export default class Scanner extends Component { 
    constructor(){ 
    super(); 
    this.onBarCodeRead = this.onBarCodeRead.bind(this); 
    } 
    onBarCodeRead(e) { 
    this.setState({text: e.data}); 
    } 
    render() { 
    return (
     <View style={styles.container}> 
      <Camera 
      ref={(cam) => { 
       this.camera = cam; 
      }} 
      onBarCodeRead={this.onBarCodeRead} 
      style={styles.preview} 
      aspect={Camera.constants.Aspect.fill}> 
      </Camera> 
     </View> 
    ); 
    } 
} 

const styles = StyleSheet.create({ 
    ... 
}); 

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

두 페이지 모두 정상적으로 작동하며 로그인 페이지를 통해 내 서비스에 로그인 할 수 있습니다. 하지만 일단 로그인하면 스캐너 구성 요소 페이지를 렌더링하는 루트 구성 요소는 어떻게 얻을 수 있습니까?

답변

0

열쇠는 여기에 setState를 호출이 될 때마다 호출 렌더링 즉 :

는 현재 상태로 nextState의 얕은 병합을 수행합니다. 이는 이벤트 핸들러에서 UI 업데이트를 트리거하는 데 사용하는 기본 방법이며 서버 요청 콜백입니다. https://facebook.github.io/react/docs/react-component.html#setstate

그래서 (이 경우에 사용자 로깅)이 loggedIn 상태를 확인하고 조건부 콘텐츠를 렌더링함으로써 달성 될 수있는 상태의 변화에 ​​기초하여 구성 요소의 컨텐츠를 업데이트하는 단계를 포함한다.

import React, { Component } from 'react'; 
import './App.css'; 


const ContentA =() => (
    <div> 
     <h1>Filled with content A</h1> 
    </div> 
); 

const ContentB =() => (
    <div> 
     <h1>Filled with content B</h1> 
    </div> 
); 


class App extends Component { 

    state = { 
     loggedIn: false 
    }; 

    logIn =() => { 
     this.setState({ 
      loggedIn: !this.state.loggedIn 
     }) 
    }; 

    render() { 

    const content = this.state.loggedIn ? <ContentA/> : <ContentB/>; 
    return (
     <div> 
      {content} 
      <button onClick={this.logIn}>Clicky</button> 
     </div> 
    ); 
    } 
} 

export default App; 

버튼을 클릭 할 때마다, setState를 호출이 만들어지고, 구성 요소가 다시 렌더 this.state.loggedIn의 값에 기초하여 :

는 예를 들어 다음의 코드를 고려한다.

호프가 도움이되고 행운을 빕니다.