rect-router-dom 4.0如何在js中控制跳转,url变化了,this.prop.children却没有更新

发布于 2022-09-05 19:32:05 字数 1679 浏览 8 评论 0

主页面

// index.js
ReactDOM.render((
    <Router history={history}>
        <App>
            <Switch>
                <Route path='/home' component={home} />
                <Route path='/mudidi' component={mudidi} />
                <Route path='/zhuanti' component={zhuanti} />
                <Route path='/daren' component={daren} />
                <Route path='/zijiayou' component={zijiayou} />
            </Switch>
        </App>
    </Router>
    ), document.getElementById('root'));

页面1

在页面中js跳转是可以的

// view/mudidi.js

 go() {
    this.props.history.push('/home')
  }
<div  onClick={this.go.bind(this)}>mudidi</div>

组件navigator.js

组件中的js控制跳转 不行 报push is a undefined

// components/navigator.js

import createBrowserHistory from 'history/createBrowserHistory';
const history = createBrowserHistory()

class Navigation extends Component {
    goNav(item,index) {
        // 这两种方式都不行
        history.push('/' + item.path)
        this.props.history.push('/' + item.path) 
    }
    render() {
    let navHtml = this.props.navData.map((item, index)=> {
        let LinkClass = index === this.state.activeIndex ? 'active' : '';
            return <div key={index} className={'child ' + LinkClass} onClick={this.goNav.bind(this, item, index)}>
                    <span>{item.name}</span>
                </div>
        })
    }
}

图片描述

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尘世孤行 2022-09-12 19:32:05

你这样写法,Navigation的props是没有history属性的,需要通过withRouter这个高阶组件包一下Navigation:

import { withRouter } from 'react-router'

export default withRouter(Navigation);   //在其他地方使用包装后的组件

更多参考:https://reacttraining.com/rea...

野の 2022-09-12 19:32:05

你是想问没有this.props 方法?

goNav = (item,index) => {
   // 这两种方式都不行
   history.push('/' + item.path)
   this.props.history.push('/' + item.path) 
}

这样?

遗失的美好 2022-09-12 19:32:05

问题解决了吗

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文