【React Native】React Redux로 통신 처리를 View와 독립시키자

왜 필요한가



【React Native】 React Redux는 기억하는 것이 번거롭지만 사용할 수밖에 없습니다. 에서 Redux를 도입했지만 상태 변경은 UI 조작뿐만 아니라 통신을 계기로 변경될 수도 있습니다. 여기에서는 통신 처리를 어떻게 기술해 나갈까 간단하고 구체적인 도입 예를 나타냅니다.

redux-thunk



redux 는 처리의 사이에 미들웨어를 사이에 두고 유연한 대응을 가능하게 하고 있습니다만, redux-thunk 는 통상이라고 JSON 의 객체를 정의하는 action 에 함수를 기술 가능하게 해, 임의의 처리를 실행할 수 있도록(듯이) 하는 미들웨어입니다.
htps : // 기주 b. 코 m / 가에 치 / 루즈 x - 준 k

전제 라이브러리



이 기사는 "NativeBase", "React Navigation"의 도입을 전제로 하고 있습니다. 처음부터 프로젝트를 작성하는 경우에는, 다음의 기사를 참고로 환경 작성해 주세요.
【React Native】NativeBase 도입
【React Native】React Navigation을 사용해 본다(화면 천이편)

설치


$ npm install redux-thunk --save

도입 예



액션



actions.js
function requestStart() {
    return {
      type: 'REQUEST_MESSAGE',
    }
}

function receiveResponse(json) {
    return {
      type: 'REQUEST_MESSAGE_SUCCESS',
      response: json.response.prefecture
    }
}

export function fetchMessages() {
    return dispatch => {
        dispatch(requestStart())
        return fetch("http://express.heartrails.com/api/json?method=getPrefectures")
            .then(response => response.json())
            .then(function(json) {
                console.log(json);
                dispatch(receiveResponse(json))
            }).catch((response) => {
                console.log("err!");
            });
    }
}

fetchMessages()



Component로부터 호출되는 함수입니다. dispatch 호출에서 상태 변경이 발생합니다. 여기에서는 fetch를 사용하여 통신(※)을 실시, 그에 의해 스테이트 변경하고 있습니다.

※무료로 사용할 수 있는 API HeartRails (https://www.heartrails.com) 를 사용하고 있습니다.

requestStart()



통신을 개시, 통신 상황의 스테이트 「isFetching」를 true 로 하는 Action 가 됩니다.

receiveResponse()



받은 리스폰스를 리스폰스(이 경우는 도도부현의 정보)의 스테이트 「response」에 세트 하는 Action이 됩니다, 통신 종료를 위해 「isFetching」는 false로 하고 있습니다.

Reducer



reducers.js
import {combineReducers} from 'redux';

export const reducer = (state = {profile: ""}, action) => {  
    switch (action.type) {
      case 'REQUEST_MESSAGE':
        return Object.assign({}, state, {
          isFetching: true
      });

      case 'REQUEST_MESSAGE_SUCCESS':
        return Object.assign({}, state, {
          isFetching: false,
          response: action.response
      });

      default:
        return {...state}
    }
};

export const reducers = combineReducers({  
  reducer: reducer,
});

액션에 설정된 「type」에 의해 각 스테이트의 변경을 행하고 있습니다.

Component



Home.js
import React, {Component} from 'react';
import { Container, View, Header, Left, Body, Right, Button, Content, Title, Text } from 'native-base';
import { connect } from 'react-redux';
import { fetchMessages } from './redux/actions';

export class HomeContainer extends Component {
  constructor(props) {
      super(props);
  }

  getPrefecture = () => {
    this.props.fetchMessages()
  }

  displayResponse = response => {
     if (!response) {
      return "";
    }
    return response.join();
  }

  render() {
  const props = this.props;
      return (
        <Container>
          <Header>
            <Left />
            <Body>
              <Title>メイン</Title>
            </Body>
            <Right />
          </Header>
          <Content>
            <View style={{display: 'flex', alignItems: 'center'}}>
              <View style={{justifyContent: 'center'}}><Text>{this.displayResponse(this.props.response)}</Text></View>
              <Button small block transparent primary onPress={this.getPrefecture}>
                <Text>都道府県を取得</Text>
              </Button>
            </View>
          </Content>
        </Container>
      );
  }
}

const mapStateToProps = state => ({
  response: state.reducer.response,
});

const mapDispatchToProps = {
  fetchMessages
};

export default connect(mapStateToProps, mapDispatchToProps)(HomeContainer);

상태 "response"를 표시하고 있습니다 (displayResponse에서 상태 분석, 표시 용 문자로 변환). 버튼 누르기에 의해, Action의 「fetchMessages」를 사용해, 통신을 실행, 스테이트가 변화(도도부현 정보가 설정)해, 표시되는 모습을 알 수 있습니다.

실제 표시





리포지토리



본 기사에서 작성한 것은 이하에서 공개하고 있으므로, 참고로 해 주세요.
htps : // 기주 b. 코 m / k 네오 / 레아 ct 나치

좋은 웹페이지 즐겨찾기