2016-11-26 34 views
0

我試圖從https://jsonplaceholder.typicode.com/獲取數據用於實踐目的。我想用鍵入的輸入獲取/發佈,/評論等。輸入更改時使用JSON數據獲取JSON數據的問題使用redux/react

例如:當我在文本區域鍵入「上崗」,我從https://jsonplaceholder.typicode.com/posts

然後數據當我輸入「意見」,我從https://jsonplaceholder.typicode.com/comments

它與一組靜態常量ROOT_URL獲取數據= 'https://jsonplaceholder.typicode.com/posts';

當我按下按鈕時,我會用靜態url獲取數據,但是改變值並不確定如何去做。

STUCK這裏

如何修改搜索欄組件,從輸入取信息的值,然後提交表單,它會根據不同的值取數據?

我希望你能理解我的問題,謝謝!

actions.js

export const fetchInfo =() => { 
const url = `${ROOT_URL}$posts`; 
const request = axios.get(url); 
return { 
    type: FETCH_INFO, 
    payload: request 
}; 
} 
export function fetchInfoSuccess(posts) { 
    return { 
    type: FETCH_INFO_SUCCESS, 
    payload: posts 
    }; 
} 

export function fetchInfoFailure(error) { 
    return { 
    type: FETCH_INFO_FAILURE, 
    payload: error 
    }; 
} 

修改action.js(我願意去工作) 與參數(信息)

export const fetchInfo = (info) => { 
    const url = `${ROOT_URL}${info}`; 
    const request = axios.get(url); 
    return { 
     type: FETCH_INFO, 
     payload: request 
    }; 
    } 
    export function fetchInfoSuccess(posts) { 
     return { 
     type: FETCH_INFO_SUCCESS, 
     payload: posts 
     }; 
    } 

    export function fetchInfoFailure(error) { 
     return { 
     type: FETCH_INFO_FAILURE, 
     payload: error 
     }; 
    } 

SearchBarContainer.js

const mapDispatchToProps = (dispatch) => { 
    return { 
    fetch:() => { 
     dispatch(fetchInfo()).then((response) => { 
      !response.error ? dispatch(fetchInfoSuccess(response.payload)) : dispatch(fetchInfoFailure(response.payload)); 
      }); 
    } 
    } 
} 

SearchBarComponent.js

export default class SearchBar extends Component { 
     constructor(props) { 
     super(props) 

     this.state = {info: ''}; 
    } 

    onInputChange = (e) => { 
     this.setState({info: e.target.value}); 
    } 

     handleOnSubmit = (e) => { 
     e.preventDefault(); 
     this.props.fetch(); 
    } 

    render() { 
     return (
    <div> 
    <form onSubmit={this.handleOnSubmit}> 
    <input onChange={this.onInputChange}/> 

      <button type="submit">Search</button> 
     </form> 
     </div> 
     ) 
    } 
    } 

STUCK這裏

如何修改搜索欄組件,從輸入取信息的值,然後提交表單,它會根據不同的值取數據?

+0

更改此<輸入的onChange = {this.onInputChange}到<輸入的onChange = {this.onInputChange} /> – maheshiv

回答

0

正如在註釋變更輸入部件有兩個事件操作(handleOnSubmit,onInputChange)提到

<input onChange={this.onInputChange} /> 

綁定當前實例this。 在handleOnSubmit方法,傳遞信息的狀態值

handleOnSubmit (e) { 
    e.preventDefault(); 
    this.props.fetchInfo(this.state.info); 
} 

這可以幫助你https://facebook.github.io/react/docs/forms.html

+0

它是一個錯字,但不是問題的解決方案,我只是無法弄清楚,如何將信息狀態傳遞到函數獲取中,因爲我得到了未定義的信息。 – Polisas

+0

你可以在fetchInfo this.props.fetchInfo(this.state.info)中傳遞this.state.info;' – maheshiv

+0

已經在這裏發佈之前發佈了,問題是,我得到未定義的值。 – Polisas