2016-09-08 3 views
0

저는 최근에 React Native로 놀아 왔고, 모든 구성 요소들 사이에서 공유 상태를 달성하기 시작하면서, 더 정확하게 나의 상태를 관리하는데 관심이 생겼습니다.반응 setState/Flux - 항상 재 렌더링을 트리거합니까?

물론 대답은 Flux입니다. 일부 고급 솔루션 (예 : Redux, Alt, MobX)을 사용하기 전에 Flux 운영자 인 작은 도구 하나를 사용하여 원시 구조 자체를 이해해야한다고 생각했습니다.

import React, { Component } from 'react'; 
import { AppRegistry, Text, View } from 'react-native'; 

import EventEmitter from 'EventEmitter'; 
import { Dispatcher } from 'flux'; 

class Store extends EventEmitter { 
    list = []; 

    actions = { 
    add: title => dispatcher.dispatch({ type: 'add', payload: { title } }) 
    }; 

    handle = ({ type, payload }) => { 
    switch(type) { 
    case 'add': this.add(payload.title); break; 
    } 
    }; 

    add(title) { 
    this.list.push(title); 
    this.emit('change'); 
    } 
} 

const store = new Store(), dispatcher = new Dispatcher(); 

dispatcher.register(store.handle); 

class App extends Component { 
    state = { list: store.list }; 

    componentWillMount() { 
    this.listener = store.addListener('change',() => this.setState({ list: store.list })); 
    } 

    componentDidMount() { 
    setInterval(() => store.actions.add(new Date().getTime()), 1000); 
    } 

    componentWillUnmount() { this.listener.remove(); } 

    render() { 
    return (
     <View style={{ marginTop: 20 }}> 
     <Text>{JSON.stringify(this.state.list)}</Text> 
     </View> 
    ); 
    } 
} 

AppRegistry.registerComponent('straightforwardFlux',() => App); 

뷰 계층의 공지 사항, 우리는 저장소가 업데이트 될 때이 상태로 연결되어 있기 때문에 자연스럽게 뷰가 다시 렌더링됩니다 {JSON.stringify(this.state.data)} 있습니다.

{JSON.stringify(store.data)}으로 변경하면보기가 다시 렌더링됩니다! 뷰에 직접 영향을주는 상태가 변경되었을 때만 뷰를 업데이트해야하기 때문에 이런 일이 발생하지 않아야합니다.이 경우에는 뷰에 렌더링 된 상태가 전혀 없습니다. 내가 여기서 뭔가를 놓치고 있니? 왜 우리는이 행동을 접하게 될까요?

이것은 또 다른 질문으로 이어집니다. 상태가 바뀔 때마다 render()가 호출됩니까? 보기 레이어가 보이는 방식에 영향을주지 않더라도? 이것에 대해 살펴 봤는데 두 가지 대답이 있습니다. 하나는 yes라고 말하면 componentShouldUpdate()은 기본적으로 true를 반환합니다. 즉, 여기에서 변경해야 할 사항이있는 경우 (그렇다면 어떻게?), 다른 하나는 단순히 no 일뿐입니다. 각 setState()으로 업데이트되지 않습니다.

전반적으로이 구현이 정확합니까? documentation

답변

1

...

setState를()는 항상 트리거 조건 렌더링 로직이 shouldComponentUpdate에서 구현되지 않는 한 재 렌더링(). 변경 가능한 객체가 사용되고 있고 shouldComponentUpdate()에서 로직을 구현할 수없는 경우 새 상태가 이전 상태와 다른 경우에만 setState()를 호출하면 불필요한 재 렌더링을 피할 수 있습니다.

tl; dr; React가보기를 분석하지 않아 어떤 상태에 있는지 명확히 알지 못합니다. 최적화 할 때까지는 shouldComponentUpdate()으로 최적화해야합니다.

shouldComponentUpdate(nextProps, nextState) { 
    // check if your view's attributes changes 
    let check1 = nextState.foo != this.state.foo 
    let check2 = nextState.bar != this.state.bar 

    // if return is true, the component will rerender 
    return check1 || check2 
} 
+0

그게 전부입니다. Flux 구현 자체에 대한 생각? 그것은 유효한가? – user5470921