質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
React Native

React Nativeは、ネイティブモバイルアプリ(iOS/Android)を作成できるJavaScriptフレームワークです。Reactと同じ設計のため、宣言的なコンポーネントでリッチなUIを開発することが可能です。

Redux

Reduxは、JavaScriptアプリケーションの状態を管理するためのオープンソースライブラリです。ReactやAngularで一般的にユーザーインターフェイスの構築に利用されます。

Q&A

解決済

1回答

289閲覧

React Nativeでredux-sagaが機能しない問題

tomoya_ios

総合スコア6

React Native

React Nativeは、ネイティブモバイルアプリ(iOS/Android)を作成できるJavaScriptフレームワークです。Reactと同じ設計のため、宣言的なコンポーネントでリッチなUIを開発することが可能です。

Redux

Reduxは、JavaScriptアプリケーションの状態を管理するためのオープンソースライブラリです。ReactやAngularで一般的にユーザーインターフェイスの構築に利用されます。

0グッド

2クリップ

投稿2019/10/26 11:59

編集2019/10/26 12:18

前提

React Native + ReduxでGitHubのリポジトリを検索できるアプリを作成しています。
非同期処理の部分でredux-sagaを使用しています。

想定している流れとしては以下の通りです。

  1. SearchBarにテキストを入力するたびにonChangeTextでactionをdispatchする。(問題ない)
  2. Middlewareで 1 の時にdispatchされるactionを監視する(問題あり)
  3. APIを叩いて取得したリポジトリを包んでreducerにsuccessかfailのactionをdispatch(問題あり)
  4. reducerで新たなstateを作成してstoreを更新(問題ありかも)
  5. FlatListでstateの状態を監視してリポジトリの状態が変わったら、UIに反映させる(問題ありかも)

ゴール

SearchBarで onChnageTextのたびにAPIを叩いてリポジトリを取得し、FlatListに表示する。
※ Javascirpt初心者のため記法など雑な部分が散見されますがご容赦頂ければ幸いです。

現状の把握と問題点の仮説

ここまでで確認したことを簡潔にまとめると

・ ActionCreatorは問題なく機能している(ActionはDispatchされている)

です。テキスト入力のたびにdispatchされるactionは想定ではmiddlewareで止まり、reducerには流れません。
middlewareではsuccessかfailの別のactionをdispatchするようにしています。
しかし、実際にはreducerにテキスト入力のたびにdispatchされるactionが流れています。
(一時的にreducerにテキスト入力のたびにdispatchされるactionのcaseを追加して確かめました)

また、前提の 4,5 を問題ありかもにしたのはreducerで initialState に適当なオブジェクトを入れてもFlatListに反映されなかったためです。

大きく分けて
・ 前提における 2, 3 が問題。つまり redux-saga の扱いに問題がある。
・ 前提における 4, 5 が問題。つまり ReducerとStore、Componentの連携に問題がある。
のどちらかだと考えています。

解決の糸口になるようなアドバイスを頂ければ幸いです。

コード

  • Component(問題となるFlatListを使用しているComponent)

このアプリではSearchBarの onChangeText と連動してリアルタイムでAPIを叩いています。
そのため、表示する責務だけを担う Repo_FlatList では makeStateToProps だけを指定し、あえて makeDispatchToPropsnullにしています。

import React, {Component} from 'react'; import {View, Text, FlatList} from 'react-native'; import {connect} from 'react-redux'; export class Repo_FlatList extends Component { render() { return( <FlatList data={this.props.repos} renderItem={({repo}) => <View style={styles.cell}> <Text style={styles.text} >{repo.name}</Text> </View>} /> ) } } const styles = { cell: { flexDirection: 'row', borderStyle: 'solid', borderWidth: 0.5, borderColor: '#bbb', }, text: { padding: 10, fontSize: 18, }, } const mapStateToProps = state => ({ repos: state.responseHandler.repos }) export default connect(mapStateToProps, null)(Repo_FlatList);
  • Component(SearchBarの部分)
import React, {Component} from 'react'; import {SearchBar} from 'react-native-elements'; import {bindTextChangedAction} from '../actions/ui_action'; import {fetchAction} from '../actions/model_action'; import {connect} from 'react-redux'; export class Repo_SearchBar extends Component { render() { return( <SearchBar round placeholder="Search" onChangeText={text => {this.props.bindTextChangedAction(text); this.props.fetchAction(text)}} value={this.props.searchText} /> ) } } const mapStateToProps = state => ({ searchText: state.bindTextChanged.searchText }) const mapDispatchToProps = { bindTextChangedAction,fetchAction } export default connect(mapStateToProps, mapDispatchToProps)(Repo_SearchBar);
  • ActionCreator(fetchの部分)
import {FETCH_REPOSITORY, FETCHREQUEST_SUCCESS, FETCHREQUEST_FAILE} from "../constants/constants" export const fetchAction = text => { return {type: FETCH_REPOSITORY, payload: text} } export const requestSuccess = repos => { return {type: FETCHREQUEST_SUCCESS, payload: repos} } export const requestFaile = e => { return {type: FETCHREQUEST_FAILE, payload: e.message} }
  • reducer
import { FETCHREQUEST_FAILE, FETCHREQUEST_SUCCESS, FETCH_REPOSITORY } from "../constants/constants"; const initialState = { repos: [] } const responseHandler = (state = initialState, action) => { switch(action.type) { case FETCHREQUEST_SUCCESS: return Object.assign({}, state, {repos: action.payload}); case FETCHREQUEST_FAILE: return Object.assign({}, state, {repos: action.payload}); default: return state } } export default responseHandler;
  • Middelware(fetchする部分)
import {call, put, takeEvery, take} from 'redux-saga/effects'; import {FETCH_REPOSITORY} from '../constants/constants'; import {requestSuccess, requestFaile} from '../actions/model_action'; function* fetchRepos(action) { while(true) { const action = yield take(FETCH_REPOSITORY) const text = action.payload try { const repos = yield call(fetchAsync, text) yield put(requestSuccess(repos)) } catch(e) { yield put(requestFaile(e.message)) } } } function* fetchAsync(text) { return fetch(`https://api.github.com/search/repositories?q=${text}+in:name&sort=stars`) .then(response => response.json(JSON.parse)) .then(json => JSON.stringify(json)) .catch((e) => { throw(e)}) } export default fetchRepos;
  • Middelware(root)
import { all } from 'redux-saga/effects'; import {fetchRepos} from './watchFetchAction'; export default function* rootSaga() { yield all([fetchRepos]) }
  • Store
import { createStore, combineReducers, applyMiddleware} from "redux"; import createSagaMiddleware from 'redux-saga'; import bindTextChanged from './src/reducers/ui_reducer'; import responseHandler from './src/reducers/model_reducer'; import fetchRepos from './src/middleware/watchFetchAction'; const rootReducer = combineReducers({bindTextChanged, responseHandler}); const configureStore = () => { const sagaMiddleware = createSagaMiddleware(); const store = createStore(rootReducer, applyMiddleware(sagaMiddleware)); sagaMiddleware.run(fetchRepos); return store } export default configureStore;

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

こんにちは

以下の修正が必要と思われます。

(1) fetchAsync

主な修正点は以下の3点です。

  • fetchAsync はジェネレーター関数にする必要がないので、 function の後の * は不要
  • response.json() の引数に与えている、 JSON.parse が不要
  • 検索に該当したレポジトリー情報の配列は、レスポンスの中の items プロパティを取得する。

修正前

function* fetchAsync(text) { return fetch(`https://api.github.com/search/repositories?q=${text}+in:name&sort=stars`) .then(response => response.json(JSON.parse)) .then(json => JSON.stringify(json)) .catch((e) => { throw(e)}) }

修正後

function fetchAsync(text) { return fetch(`https://api.github.com/search/repositories?q=${text}+in:name&sort=stars`) .then(response => response.json()) .then(data => data.items) .catch(e => { throw e; }); }

(2) Repo_FlatList#render

修正点は主に以下の2つです。

  • renderItem に与える関数の引数のオブジェクトに、配列要素が入ってくるプロパティは item と決まっています。
  • keyExtractor を追加して、key を生成させるようにしないとエラー(ないし警告)が表示されると思われます。

修正前

jsx

1 render() { 2 return( 3 <FlatList 4 data={this.props.repos} 5 renderItem={({repo}) => 6 <View style={styles.cell}> 7 <Text style={styles.text} >{repo.name}</Text> 8 </View>} 9 /> 10 ) 11 }

修正後

jsx

1 render() { 2 return( 3 <FlatList 4 data={this.props.repos} 5 renderItem={({item}) => 6 <View style={styles.cell}> 7 <Text style={styles.text} >{item.name}</Text> 8 </View> 9 } 10 keyExtractor={item => item.name} 11 /> 12 ) 13 }

以下は、動作確認のため私の手元でご質問に挙げられているコードをコピペして、各ファイルを作成してアプリを構成し、上記の修正後、iOSシミュレータに表示させた画面です。

イメージ説明

なお上記のサンプルでは、Repo_FlatListcomponentDidMount に以下を追加しています。

javascript

1 componentDidMount() { 2 this.props.dispatch(fetchAction('React')); 3 }

以上、参考になれば幸いです。

投稿2019/10/26 17:02

編集2019/10/27 03:53
jun68ykt

総合スコア9058

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tomoya_ios

2019/10/27 05:49

ご回答ありがとうございます!正常に動作しました! ・JSONのパース ・renderItemの引数はitemと決まっていること ・keyExtractorの役割 などとても参考になりました! 引き続き自分でも理解を深めていきたいと思います! お忙しい中お時間をとって回答して頂き本当にありがとうございます。
jun68ykt

2019/10/27 07:10

どういたしまして。 > 正常に動作しました! とのことで、よかったです????
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問