2017-01-16 10 views
0

ユーザーが入力ボックスにテキストを入力できるようにするため、これに基づいてAPIを検索したいと考えています。私はreduxredux-thunkを使用しています。 API呼び出しに引数として入力されたテキストをどのように渡すべきかは不明です。引数をreact-reduxのストアを更新するメソッドに渡す

IはReduxのとサンクを使用しなかった場合、私は

this.state = { 
    movie: '' 
} 

コンポーネントの状態を設定するであろうし、その後input type=textに私はe.target.valuemovieonChangeを更新するであろう。 reduxと反応させるときに取るべきアプローチは何ですか?

私のコードは次のようになります。 reduxを始めるとき

import React, {Component} from 'react'; 
import {render} from 'react-dom'; 
import {createStore, applyMiddleware} from 'redux'; 
import {Provider, connect} from 'react-redux'; 
import thunk from 'redux-thunk'; 
import axios from 'axios'; 

function reducer(state = 0, action) { 
    switch (action.type) { 
    case 'GET_MOVIE': 
     return action.data; 
    default: 
     return state; 
    } 
} 

const store = createStore(
    reducer, 
    applyMiddleware(thunk) 
); 


class App extends Component { 

    getMovie(){ 
     this.props.getMovie(); 
    } 

    render() { 
     return(
      <div> 
       <input type='text'> 
       <input type='submit' onClick={this.props.getMovie}> 
      </div> 
     ) 
    } 
} 

function getMovie(movie){ 
    return function(dispatch) { 
     axios.get('http://www.omdbapi.com/?t=' + movie) 
     .then(function(data){ 
      dispatch(resolvedGetMovie(data.data)); 
     }) 
    } 
} 

function resolvedGetMovie(data){ 
    return { 
     type: ' 
      GET_MOVIE ', 
     data: data 
    } 
} 

function mapStateToProps(state) { 
    return { 
     movie: state 
    } 
} 

function mapDispatchToProps(dispatch) { 
    return { 
     getMovie :() => dispatch(getMovie()) 
    } 
} 

const ConnectedApp = connect(mapStateToProps, mapDispatchToProps)(App); 

render(
    <Provider store={store}> 
     <ConnectedApp /> 
    </Provider>, 
    document.getElementById('root') 
) 

答えて

1

それが離れて運ばれ、減速内のすべてのアプリケーションの状態を置く取得するのは簡単です。しかし、フォームフィールド、UI関連の状態、および特定のコンポーネントにのみ関連するその他の状態については、これをcomponentの状態で保存すると有益です。あなたが提供するたとえば、あなたは、コンポーネントの状態にinput値を追跡する必要があり、その後、例えば、あなたのアクション(getMovie

にその値を渡す:

class App extends Component { 
    constructor(props) { 
     this.state = { 
      movie: '' 
     }   
    } 

    handleChange(e) { 
     this.setState({ 
      movie: e.target.value 
     }); 
    } 

    handleSubmit() { 
     const {movie} = this.state; 
     this.props.getMovie(movie); 
    } 

    render() { 
     const {movie} = this.state; 

     return(
      <div> 
       <input 
        type='text' 
        onChange={this.handleChange.bind(this)} 
        value={movie} 
       /> 
       <input type='submit' onClick={this.handleSubmit.bind(this)}> 
      </div> 
     ) 
    } 
} 
関連する問題