反应路由器 Dom 历史

React Router Dom History

我正在尝试在某些功能出现后在我的 React 应用程序中导航。通常我会使用 window.location 来执行此操作,但是,我被告知要避免在像我这样的单页应用程序中刷新页面。我正在努力让它导航离开。

我正在使用 react-router-dom 和 react-dnd。由于 react-dnd,历史并没有像往常一样被传递下去。

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { DragSource } from 'react-dnd'
import ItemTypes from '../ItemTypes'
import { BrowserRouter } from 'react-router-dom'
const style = {
    fontSize: '126px', 
    'cursor': 'move',   
}

const boxSource = {
    beginDrag(props) {
        return {
            name: props.name,
        }
    },

    endDrag(props, monitor) {
        // const item = monitor.getItem()
        const dropResult = monitor.getDropResult()

        if (dropResult) {
            // window.location.href = 'http://localhost/book/'
            // what do i put here to navigate away
        }
    },
}


class Key extends Component {
    static propTypes = {
        connectDragSource: PropTypes.func.isRequired,
        isDragging: PropTypes.bool.isRequired,
        name: PropTypes.string.isRequired,
    }

    render() {
        const { isDragging, connectDragSource } = this.props
        const { name } = this.props
        const opacity = isDragging ? 0.4 : 1

        return connectDragSource(<div style={{ ...style, opacity }}>{name}</div>)
    }
}

// @DragSource(ItemTypes.BOX, boxSource, (connect, monitor) => ({
//  connectDragSource: connect.dragSource(),
//  isDragging: monitor.isDragging(),
// }))

export default DragSource(ItemTypes.BOX, boxSource, (connect , monitor) => {
    return {
        connectDragSource: connect.dragSource(),
        isDragging: monitor.isDragging(),
    }
})(Key)

我尝试将 browserHistory 与 react-router 一起使用,但 BrowserRouter 默认情况下不会将 history 作为 prop。

如果我必须使用 window.location 请告诉我。

尝试使用推送:

if (dropResult) {
  history.push('/book')
}

有关详细信息,请参阅