处理axios get.request的动作创建者,其中包含对param的状态访问权限

时间:2016-09-08 22:12:46

标签: asynchronous reactjs react-redux redux-thunk

我正在尝试将某个值从组件传递给使用axios执行get请求的动作创建者。我试图遵循Dan Abramov的这种模式:

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return (dispatch, getState) => {
    const {items} = getState().otherReducer;

    dispatch(anotherAction(items));
  }
}

然而,我无法使其发挥作用。我认为我在两个层面上遇到了麻烦:我的组件和我的动作创建者。有一些帮助会很棒。

我的组件:

const timeR = ({ 
  selectedTimeRange,
  timeRange = [],
  onTimeChange }) => {
  return (
    <div>
      <div>
        Filters:
        <div>
          Year:
          <select
            defaultValue={selectedTimeRange}
            onChange={onTimeChange}>
            <option value="all" >All</option>
            {timeRange.map((y, i) =>
              <option key={i} value={y}>{y}</option>
            )}
          </select>
        </div>
    </div>
  </div>
  );
}


function mapStateToProps(state) {
    var range = ['30daysAgo', '15daysAgo', '7daysAgo'];
  return {
      selectedTimeRange: state.timeReducer.timerange[0],
      timeRange: range 
  };
};

const mapDispachToProps = (dispatch) => {
  return {
  onTimeChange: (e) => {dispatch (onSetTimeRange(e.target.value));},

  };
};

const TimeRange = connect(mapStateToProps, mapDispachToProps)(timeR);

export default TimeRange;

这个组件给我一个下拉菜单。选择时间范围时,例如'30daysAgo',它会更新我的redux存储状态,以便我可以从我的reducer访问该值。

以下是与我的下拉菜单相关联的操作:

export function onSetTimeRange(timerange) {
 return {
        type: 'SET_TIME_RANGE',
        timerange
    }
}

这是处理axios.get的行动:

export const fetchgadata = () => (dispatch) => {
    dispatch({
        type: 'FETCH_DATA_REQUEST',
        isFetching:true,
        error:null
  });

var VIEW_ID = "ga:80820965";

return axios.get("http://localhost:3000/gadata", {
  params: {
    id: VIEW_ID
  }
}).then(response => {
      dispatch({
            type: 'FETCH_DATA_SUCCESS',
            isFetching: false,
            data: response.data.rows.map( ([x, y]) => ({ x, y }) )
      });
    })
    .catch(err => {
      dispatch({
            type: 'FETCH_DATA_FAILURE',
            isFetching:false,
            error:err
      });
      console.error("Failure: ", err);
    });
};

我的问题:

如何将这两个动作结合在一起。最后,我希望能够在我的下拉菜单中执行onChange时,使用从菜单中选择的值作为axios.get请求的参数调用操作。

我觉得我需要嵌套两个动作创作者。我试过这个但是不起作用(终端"fetchgadata" is read-only错误)

export const SET_TIME_RANGE = 'SET_TIME_RANGE';
export function onSetTimeRange() {
  return (dispatch, getState) => {
    const {VIEW_ID} = getState().timerange;

    dispatch(fetchgadata = (VIEW_ID) => (dispatch) => {
    dispatch({
        type: 'FETCH_DATA_REQUEST',
        isFetching:true,
        error:null,
        id:VIEW_ID,
  });
  });

return axios.get("http://localhost:3000/gadata", {
  params: {
    id: VIEW_ID
  }
}).then(response => {
      dispatch({
            type: 'FETCH_DATA_SUCCESS',
            isFetching: false,
            data: response.data.rows.map( ([x, y]) => ({ x, y }) )
      });
    })
    .catch(err => {
      dispatch({
            ype: 'FETCH_DATA_FAILURE',
            isFetching:false,
            error:err
      });
      console.error("Failure: ", err);
    });
}
  }

编辑:

API调用的reducers:

const initialState = {data:null,isFetching: false,error:null};
export const gaData = (state = initialState, action)=>{
    switch (action.type) {
        case 'FETCH_DATA_REQUEST':
        case 'FETCH_DATA_FAILURE':
        return { ...state, isFetching: action.isFetching, error: action.error };

        case 'FETCH_DATA_SUCCESS':
        return Object.assign({}, state, {data: action.data, isFetching: action.isFetching,
                 error: null });
        default:return state;

    }
};

下拉列表:

const items = [{timerange: '30daysAgo'},{timerange: '15daysAgo'},{timerange: '7daysAgo'}] 

const timeReducer = (state = { 
  timerange: items 
  }, action) => { 
    switch (action.type) {
      case 'SET_TIME_RANGE':
      console.log(state,action);
              return {
        ...state,
        timerange: action.timerange,
      };
    default:
      return state;

        }
    }

1 个答案:

答案 0 :(得分:1)

我在axios.get请求的捕获中看到一个小错误,它显示为ype: FETCH_DATA_FAILURE。否则,你可以为我添加减速机,我不会在那里看到它吗?如果我理解正确,您需要一个动作来更新两个不同的状态,在这种情况下,您只需调度一个动作并将其添加到两个减速器。真的是最好的证明:

//axios call
axios.get("some route", { some params } )
.then(response => { 
    dispatch({
      type: UPDATE_TWO_THINGS,
      payload: some_value
    })
}) .... catch, etc

//reducer 1
import { UPDATE_TWO_THINGS } from 'types';

const INITIAL_STATE = { userInfo: '' };

export default function (state = INITIAL_STATE, action) {
  switch(action.type) {
   case UPDATE_TWO_THINGS:
     return {...state, userInfo: payload };
  }

  return state;
}

//reducer 2
import { UPDATE_TWO_THINGS } from 'types';

const INITIAL_STATE = { businessInfo: '' };

export default function (state = INITIAL_STATE, action) {
  switch(action.type) {
   case UPDATE_TWO_THINGS:
     return {...state, businessInfo: payload };
  }

  return state;
}

希望这会有所帮助,但如果没有,请告诉我,我会尽我所能让这个与你合作!谢谢你的询问!