2016-08-01 39 views
0

我的目標是基本上在react-redux中做一個基本的GET請求。我知道如何使用POST來做到這一點,但不使用GET,因爲沒有事件觸發該動作。如何在react-redux中正確執行GET請求?

繼承人的行動

export function getCourses() { 
    return (dispatch) => { 

    return fetch('/courses', { 
     method: 'get', 
     headers: { 'Content-Type': 'application/json' }, 
    }).then((response) => { 
     if (response.ok) { 
     return response.json().then((json) => { 
      dispatch({ 
      type: 'GET_COURSES', 
      courses: json.courses 
      }); 
     }) 
     } 
    }); 
    } 
} 

我在哪裏可以觸發此獲取數據的代碼?在組件中?

import React from 'react'; 
import { Link } from 'react-router'; 
import { connect } from 'react-redux'; 
import { getCourses } from '../actions/course'; 


class Course extends React.Component { 

    componentDidMount() { 
     this.props.onGetCourses(); 
    } 

    allCourses() { 
    console.log(this.props.onGetCourses()); 
     return this.props.courses.map((course) => { 
     return(
      <li>{ course.name }</li> 
     ); 
     }); 

     return this.props 
    } 

    render() { 
    return (
     <div> 
     <ul> 
      { this.allCourses() } 
     </ul> 

     </div> 
    ) 
    } 
} 

const mapStateToProps = (state) => { 
    return { 
    courses: state.course.courses 
    } 
} 

const mapDispatchToProps = (dispatch) => { 
    return { 
    onGetCourses:() => dispatch(getCourses) 
    } 
} 

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

我試過這個,但它不起作用。

課程減速

const initialState = { 
    courses: [] 
}; 



export default function course(state= initialState, action) { 

    switch (action.type) { 
    case 'GET_COURSES': 
     return Object.assign({}, state, { 
     courses: action.courses 
     }) 
    default: 
     return state; 
    } 


} 

回答

1

首先,onGetCourses:() => dispatch(getCourses)應改爲onGetCourses:() => dispatch(getCourses())(您需要實際調用動作創建者)。

當涉及到你應該調用動作的地方時,就像你所做的那樣,在componentDidMount中執行它絕對沒問題。

+0

傻我,謝謝,現在它顯示所有的數據! – sinusGob

0
  1. 在你沒有注意到的情況下,你有兩個返回的在您的allCourses()。
  2. 我在代碼庫中有類似的代碼,但是我並沒有在fetch和response.json()前面使用return,因爲函數應該返回操作對象。
相關問題