React Redux动作有效负载不在componentDidMount中

时间:2017-06-08 15:41:26

标签: reactjs react-redux

我有一个我在componentWillMount中调用的动作创建者,使用setState将该动作有效负载的返回分配给状态。但是,在componentDidMount中,我无法访问该属性,因为异步调用尚未完成。在compoentDidMount中访问此数据的正确方法是什么?

//component
class Dashboard extends Component {

componentWillMount() {
    this.setState(this.props.getUser());
  }

componentDidMount() {
    // this.state.user isn't available yet
}

render(){
  return(...);
}
}

//action
export function getUser() {
  return async function (dispatch) {
     const user = await axios.get(`${API_URL}user?token=${token}`);
     return dispatch({
      type: USER,
      payload: user,
     });
    } 
  };
}

2 个答案:

答案 0 :(得分:2)

Axios返回一个承诺,你必须等到它结算。然后像这样发送成功动作,

export function getUser() {
  return function (dispatch) {
     axios.get(`${API_URL}user?token=${token}`)
        .then(user => {
             return dispatch(getUserSuccess(user));
        }).catch(error => {
            throw error;
        });
    } 
  };

  export function getUserSuccess(user) {
    return {type: USER, payload: user};
  }

另请注意,您需要mapStateToProps才能将user带到您的组件。然后,您可以使用组件中的this.props.user访问它。它应该是这样的。

UserPage.propTypes = {
  user: PropTypes.object.isRequired
};

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

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({getUser}, dispatch)
  };
}

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

最后,您可以像这样访问用户。

  render() {
    const {user} = this.props;
    return(
      <div>
        <div>user.name</div>
      </div>
    );
  }

答案 1 :(得分:0)

您需要使用componentWillReceiveProps来执行此操作,例如:

componentWillReceiveProps(nextProps) {
   if (nextProps.user !== this.state.user) {
       this.setState({
           user: nextProps.user
       });
   }
}

现在您可以在组件中使用user

Here您可以找到更多信息。

相关问题