簡體   English   中英

如何使用具有react-router路由轉換的自定義組件?

[英]How to use a custom component with react-router route transitions?

確認導航”一文解釋了如何在轉換鈎子中使用瀏覽器確認框。 精細。 但我想使用自己的對話框。 如果我要使用history模塊中的方法,我認為這是可能的。 是否可以使用react-router中的setRouteLeaveHook執行此操作?

核心問題是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)
      })
    }
  })
}

我通過設置布爾值開啟狀態來確定是否已確認導航(使用react-router 2.8.x)。 正如它在您發布的鏈接中所述: https//github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

返回false以防止轉換而不提示用戶

但是,他們忘記提到鈎子也應該是未注冊的,請看這里這里

我們可以使用它來實現我們自己的解決方案如下:

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
};

發布攔截后退按鈕甚至路線更改的解決方案。 這適用於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
};

以上是偉大的,除非用戶回到歷史。 像下面這樣的東西應該解決問題:

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

這是我的解決方案。 我創建了一個自定義對話框組件,您可以使用它來包裝應用程序中的任何組件。 您可以打包標題,這樣就可以在所有頁面上顯示它。 它假設您使用的是Redux Form,但您可以簡單地將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>
    )
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM