2016-08-01 37 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,因为函数应该返回操作对象。
相关问题