如何使用具有react-router路由转换的自定义组件?

时间:2016-02-08 17:11:43

标签: javascript react-router

文章Confirming Navigation说明了如何在转换挂钩中使用浏览器确认框。精细。但我想使用自己的对话框。如果我使用history模块中的方法,我认为这是可能的。是否可以使用react-router中的setRouteLeaveHook执行此操作?

5 个答案:

答案 0 :(得分:15)

核心问题是setRouteLeaveHook期望钩子函数同步返回其结果 。这意味着您没有时间显示自定义对话框组件,等待用户单击选项,然后然后返回结果。所以我们需要一种方法来指定异步钩子。这是我写的实用函数:

// Asynchronous version of `setRouteLeaveHook`.
// Instead of synchronously returning a result, the hook is expected to
// return a promise.
function setAsyncRouteLeaveHook(router, route, hook) {
  let withinHook = false
  let finalResult = undefined
  let finalResultSet = false
  router.setRouteLeaveHook(route, nextLocation => {
    withinHook = true
    if (!finalResultSet) {
      hook(nextLocation).then(result => {
        finalResult = result
        finalResultSet = true
        if (!withinHook && nextLocation) {
          // Re-schedule the navigation
          router.push(nextLocation)
        }
      })
    }
    let result = finalResultSet ? finalResult : false
    withinHook = false
    finalResult = undefined
    finalResultSet = false
    return result
  })
}

以下是如何使用它的示例,使用vex显示对话框:

componentWillMount() {
  setAsyncRouteLeaveHook(this.context.router, this.props.route, this.routerWillLeave)
}
​
routerWillLeave() {
  return new Promise((resolve, reject) => {
    if (!this.state.textValue) {
      // No unsaved changes -- leave
      resolve(true)
    } else {
      // Unsaved changes -- ask for confirmation
      vex.dialog.confirm({
        message: 'There are unsaved changes. Leave anyway?' + nextLocation,
        callback: result => resolve(result)
      })
    }
  })
}

答案 1 :(得分:1)

我通过设置布尔值开启状态来确定是否已确认导航(使用react-router 2.8.x)。正如它在你发布的链接中所说: https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

  

返回false以防止转换而不提示用户

但是,他们忘记提及钩子也应该取消注册,请参阅herehere

我们可以使用它来实现我们自己的解决方案,如下所示:

class YourComponent extends Component {
  constructor() {
    super();

    const {route} = this.props;
    const {router} = this.context;

    this.onCancel = this.onCancel.bind(this);
    this.onConfirm = this.onConfirm.bind(this);

    this.unregisterLeaveHook = router.setRouteLeaveHook(
      route,
      this.routerWillLeave.bind(this)
    );
  }

  componentWillUnmount() {
    this.unregisterLeaveHook();
  }

  routerWillLeave() {
    const {hasConfirmed} = this.state;
    if (!hasConfirmed) {
      this.setState({showConfirmModal: true});

      // Cancel route change
      return false;
    }

    // User has confirmed. Navigate away
    return true;
  }

  onCancel() {
    this.setState({showConfirmModal: false});
  }

  onConfirm() {
    this.setState({hasConfirmed: true, showConfirmModal: true}, function () {
      this.context.router.goBack();
    }.bind(this));
  }

  render() {
    const {showConfirmModal} = this.state;

    return (
      <ConfirmModal
        isOpen={showConfirmModal}
        onCancel={this.onCancel}
        onConfirm={this.onConfirm} />
    );
  }
}

YourComponent.contextTypes = {
  router: routerShape
};

答案 2 :(得分:1)

发布拦截后退按钮甚至路线更改的解决方案。这适用于React-router 2.8或更高版本。或者甚至使用 withRouter

import React, {PropTypes as T} from 'react';

...
componentWillMount() {
        this.context.router.setRouteLeaveHook(this.props.route, this.routerWillLeaveCallback.bind(this));
    }

    routerWillLeaveCallback(nextLocation) {
        let showModal = this.state.unsavedChanges;
        if (showModal) {
            this.setState({
                openUnsavedDialog: true,
                unsavedResolveCallback: Promise.resolve
            });
            return false;
        }
        return true;
    }
}


YourComponent.contextTypes = {
    router: T.object.isRequired
};

答案 3 :(得分:0)

上面很棒,除非用户回到历史记录中。以下内容应该可以解决问题:

if (!withinHook && nextLocation) {
    if (nextLocation.action=='POP') {
        router.goBack()
    } else {
      router.push(nextLocation)
    }
}

答案 4 :(得分:0)

这是我对此的解决方案。我创建了一个自定义对话框组件,您可以使用它来包装应用程序中的任何组件。您可以打包标题,这样就可以在所有页面上显示它。它假设您使用的是Redux表单,但您只需将areThereUnsavedChanges替换为其他表单更改检查代码即可。它还使用React Bootstrap模式,您可以使用自己的自定义对话框替换它。

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { withRouter, browserHistory } from 'react-router'
import { translate } from 'react-i18next'
import { Button, Modal, Row, Col } from 'react-bootstrap'

// have to use this global var, because setState does things at unpredictable times and dialog gets presented twice
let navConfirmed = false

@withRouter
@connect(
  state => ({ form: state.form })
)
export default class UnsavedFormModal extends Component {
  constructor(props) {
    super(props)
    this.areThereUnsavedChanges = this.areThereUnsavedChanges.bind(this)
    this.state = ({ unsavedFormDialog: false })
  }

  areThereUnsavedChanges() {
    return this.props.form && Object.values(this.props.form).length > 0 &&
      Object.values(this.props.form)
        .findIndex(frm => (Object.values(frm)
          .findIndex(field => field && field.initial && field.initial !== field.value) !== -1)) !== -1
  }

  render() {
    const moveForward = () => {
      this.setState({ unsavedFormDialog: false })
      navConfirmed = true
      browserHistory.push(this.state.nextLocation.pathname)
    }
    const onHide = () => this.setState({ unsavedFormDialog: false })

    if (this.areThereUnsavedChanges() && this.props.router && this.props.routes && this.props.routes.length > 0) {
      this.props.router.setRouteLeaveHook(this.props.routes[this.props.routes.length - 1], (nextLocation) => {
        if (navConfirmed || !this.areThereUnsavedChanges()) {
          navConfirmed = false
          return true
        } else {
          this.setState({ unsavedFormDialog: true, nextLocation: nextLocation })
          return false
        }
      })
    }

    return (
      <div>
        {this.props.children}
        <Modal show={this.state.unsavedFormDialog} onHide={onHide} bsSize="sm" aria-labelledby="contained-modal-title-md">
          <Modal.Header>
            <Modal.Title id="contained-modal-title-md">WARNING: unsaved changes</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            Are you sure you want to leave the page without saving changes to the form?
            <Row>
              <Col xs={6}><Button block onClick={onHide}>Cancel</Button></Col>
              <Col xs={6}><Button block onClick={moveForward}>OK</Button></Col>
            </Row>
          </Modal.Body>
        </Modal>
      </div>
    )
  }
}