在React / Redux中设置初始状态之前等待Ajax调用

时间:2016-08-24 18:45:54

标签: reactjs redux state

我正在使用react和redux,并且想知道以下是否可能:

我正在创建一个“编辑表单”组件,我想将preselected的初始状态设置为this.props.user.preselected.id。

我可以在任何地方调用this.props.user.preselected.id,除了设置初始值的情况。我一直得到一个空值,我相信这是因为缩减器this.props.user仅在this.props.fetchSingleUser完成后出现。

是否可以将初始状态设置为当前在同一组件中提取的reducer?

class PropertyEdit extends Component {

  static contextTypes = {
    router: PropTypes.object
  };

  constructor(props) {
        super(props);
        this.state = { 
            preselected= this.props.user.preselected.id
        };       
  }


  componentWillMount() {
    this.props.fetchSingleUser(this.props.params.id);
  }

....


function mapStateToProps(state) {
  return { 
    user:state.user.single
  };
}


function mapStateToProps(state) {
  return { 
    user:state.users.single
  };
}

action.js

export function fetchSingleUser(id) {
  return function(dispatch) {
    axios.get(`${URL}/users/${id}`)
    .then(response => {
      dispatch({
        type:FETCH_USER,
        payload: response
      });
    })
   .catch(() => {
      console.log("Error ");
    });
  }
}

减速器:

const INITIAL_STATE = { single: null };

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

2 个答案:

答案 0 :(得分:1)

Verry的常见方法是为异步操作提供3个操作

<强> types.js

export const FETCH_USER_REQUEST = 'FETCH_USER_REQUEST'
export const FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS'
export const FETCH_USER_FAIL = 'FETCH_USER_FAIL'

<强> reducer.js

import {combineReducers} from 'redux';
import * as types from './types';

const isFetching = (state = false, action) => {
  switch (action.type) {
    case types.FETCH_USER_REQUEST:
      return true;
    case types.FETCH_USER_SUCCESS:
    case types.FETCH_USER_FAIL:
      return false;
    default:
      return state;
  }
};

const data = (state = {}, action) => {
  switch (action.type) {
    case types.FETCH_USER_SUCCESS:
      return action.payload.data;
  }
  return state;
};

export default combineReducers({
  isFetching,
  data
});

因此,您可以在组件中获得isFetching道具并显示/隐藏您的表单

答案 1 :(得分:0)

您认为只有在收到用户数据后才能呈现表单吗?

  • 使用redux thunk,你可以在完成提取后发出一个动作USER_LOADED
  • 此新操作会使用userLoaded = true
  • 更新redux商店
  • 然后您可以在您的react组件中传递user.loaded以显示表单
相关问题