ReactJs - 如何在下载前完成onClick - href

时间:2017-10-03 23:13:29

标签: javascript reactjs

我有一个简单的React按钮组件,单击它时应该在客户端浏览器上检索和下载数据。我遇到的问题是在数据传递到href之前触发了下载并下载了csv文件。

这是我的组件:

import { Component } from 'react';
import { connect } from 'react-redux';
import { PropTypes } from 'prop-types';
import { ManageUsersSelectors } from 'selectors/Users';
import { BatchRoleActions } from 'actions/Users';

 class UsersExportButton extends Component {
  constructor() {
    super();
    this.state = {
      users: ''
    };
  }

  getUsers(){
    const { userIds } = this.props;
    BatchRoleActions.getAllRoleUsers(userIds)
    .then((users) => {
      this.setState({ users: users});
      return  this.state.users;
    });
  }

  render() {
    return (
      <div className="roles-export-button">
        <a className="button button-default" href={this.state.users} download={'roles.csv'} onClick={() => this.getUsers()} return true>Export Csv</a>
      </div>
    );
  }
}

function mapStateToProps(state) {
  const userIds = ManageUsersSelectors.batchUserIdsSelector(state);
  return {
    userIds: userIds
  };
}

UsersExportButton.propTypes = {
   text: PropTypes.string.isRequired,
   data: PropTypes.array
};

export default connect(mapStateToProps)(UsersExportButton);

如何在下载之前获取getUsers()/ onClick函数来完成数据检索步骤?

当我调试我的代码时,我可以看到getUsers函数返回数据 - 但是在下载后触发

3 个答案:

答案 0 :(得分:0)

确保将this绑定到您的函数。在你的构造函数中,你可以这样做:

 constructor() {
    super();
    this.state = {
      users: ''
    };

    this.getUsers = this.getUsers.bind(this);
  }

或者您可以使用bind this功能:

  getUsers = () => {
    const { userIds } = this.props;
    BatchRoleActions.getAllRoleUsers(userIds)
    .then((users) => {
      this.setState({ users: users});
      return  this.state.users; // This should be removed, you can use this.state.users throughout this component.
    });
  }

答案 1 :(得分:0)

为什么不在componentDidMount生命周期方法中获取用户数据?它看起来不需要在onClick上调用。

{
  // ...
  componentDidMount() {
    this.getUsers();
  }
  // ...
  render() {
    return (
      <div className="roles-export-button">
        <a className="button button-default" href={this.state.users} download={'roles.csv'}>Export Csv</a>
      </div>
    )
  }
}

答案 2 :(得分:0)

如何手动处理默认的“链接”行为以获得更多控制权?此外,您应该尝试通过其回调执行state后访问setState

e.g。

getUsers(cb){
  const { userIds } = this.props;
  BatchRoleActions.getAllRoleUsers(userIds)
  .then((users) => {
    // note the callback of setState which is invoked
    // when this.state has been set
    this.setState({ users: users }, cb);
  });
}

const handleClick = () => {
  this.getUsers(() => {
    window.open(this.state.whatever)
  })
}

<span onClick={handleClick}>Export Csv</span>