如何从反应组件中的异步函数中获取数据,react-redux?

时间:2018-06-04 06:10:16

标签: javascript reactjs react-native redux

我是redux的新手并做出反应。我有React容器和组件,它从api请求调用中获取数据。基本上我的问题是,什么是处理还原反应的asyc功能的最佳方法。我需要帮助来获取react组件中的数据。

Container.js :(不完整,我需要帮助)

class Container extends React.Component {

  state = {
    userList: ''
  }

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

  render() {
    return (
      <div className="app">
       <Component userList={this.state.userList}/>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  userList: state.auth.userList
});

const mapDispatchToProps = (dispatch) => bindActionCreators({
  loadUserDetails
}, dispatch);

export default withRouter(connect(
  mapStateToProps,
  mapDispatchToProps
)(Container));

Componet.js :(纯组件,这里我需要渲染数据)

class Component extends React.Component {

  render() {
    return (
      <div className="component">
       {this.props.userList}
      </div>
    );
  }
}

模块/ AUTH / index.js

export const loadUserDetails = () => {
  return dispatch => {
    dispatch({
      type: types.LOAD_USER_REQUEST
    });
    request.get('/api/v1/auth', dispatch)
    .then(({ data }) => {
      if (data.success) {
        dispatch({
          type: types.LOAD_USER_SUCCESS
      payload: data.data
        });
      } else {
        dispatch({
          type: types.LOAD_USER_FAILURE,
          payload: data.message
        });
      }
    })
    .catch((err) => {
      dispatch({
        type: types.LOAD_USER_FAILURE,
        payload: 'Something went wrong, please try again.'
      });
    });
  };
};

modules / auth / actions.js:

export const LOAD_USER_REQUEST = 'auth/LOAD_USER_REQUEST';
export const LOAD_USER_SUCCESS = 'auth/LOAD_USER_SUCCESS';
export const LOAD_USER_FAILURE = 'auth/LOAD_USER_FAILURE';

modules / auth / reducers.js:

state ={
    loading: false,
    error: null,
    userList: null
}


case types.LOAD_USER_REQUEST: 
      return Object.assign({}, state, {
    loading: true
      });
    case types.LOAD_USER_REQUEST:
      return Object.assign({}, state, {
    loading: false,
        userList: payload,
      });
    case types.LOAD_USER_REQUEST:
      return Object.assign({}, state, {
    loading: flase,
    error: payload
      });

我实际上需要帮助来获取Container中的userList并将其传递给Component。因为它是一个asyc函数,我无法在Component渲染之前获取Container中的数据。如何处理这种情况?

当我在Child组件中传递userList时,我第一次没有userList数据。所以我的问题是Reactjs的循环,我应该在哪里调用loadUserList?在componentDidMount中?还是componentDidUpdate?如果是这样,我怎样才能获得数据?

当组件安装时,我无法呈现userList它的值为null。怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

一个好的选择是使用redux-saga,简单易用:

https://github.com/redux-saga/redux-saga

相关问题