为什么props.history.location.search和props.location.search不一致呢?

点击tab切换路由的query参数,在 '/?tab=a'、'/?tab=b'、'/?tab=c'来回切换,此时this.props.location.search是路由切换上一次的数据,而this.props.history.location.search是当前最新的数据,请问为什么会有这种差异?

===update===
我把代码全贴上来了,由于用了antd,所以测试会麻烦点,此时切换tab打印props就能看到

import React from 'react'
import { Menu, Icon } from 'antd'
import { withRouter, Link } from 'react-router-dom'
// import './index.scss'

class Nav extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      collapsed: false,
      menu: [
        {
          icon: 'icon-quanbu',
          name: '全部',
          tab: 'all'
        },
        {
          icon: 'icon-jingxuan',
          name: '精华',
          tab: 'good'
        },
        {
          icon: 'icon-fenxiang',
          name: '分享',
          tab: 'share'
        },
        {
          icon: 'icon-wenda',
          name: '问答',
          tab: 'ask'
        },
        {
          icon: 'icon-zhaopin',
          name: '招聘',
          tab: 'job'
        },
        {
          icon: 'icon-kaifa',
          name: '客户端开发测试',
          tab: 'dev'
        },
      ],
      menuOperation: {
        paddingLeft: 24
      }
    }
  }
  getURLSearchParams = () => {
    return new URLSearchParams(this.props.location.search)
  }
  // 菜单折叠和展开
  toggleCollapsed = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    })
  }
  // 切换 tab
  changeTab = (tab) => {
    console.log(this.props)
  }
  render() {
    return (
      <Menu
        id="nav-list"
        defaultSelectedKeys={[ this.getURLSearchParams().get('tab') || 'all' ]}
        mode="inline"
        theme="dark"
        onSelect={this.changeTab}
        inlineCollapsed={this.state.collapsed}>
        <div
          onClick={this.toggleCollapsed}
          style={this.state.collapsed ? {paddingLeft: 30} : null}
          className="menu-operation">
          <Icon type={this.state.collapsed ? 'arrows-alt' : 'shrink'} />
          <span>{this.state.count}{this.state.collapsed ? '' : '折叠'}</span>
        </div>
        {/* key 代表的是路由地址 */}
        {this.state.menu.map((item, index) => {
          return (
            <Menu.Item key={item.tab} title={item.name}>
              <Link to={`/?tab=${item.tab}`}>
              {/* <Link to={`/index/${item.tab}`}> */}
                <i className={`iconfont ${item.icon}`} />
                {!this.state.collapsed ? <span>{item.name}</span> : ''}
              </Link>
            </Menu.Item>
          )
        })}
      </Menu>
    )
  }
}

export default withRouter(Nav)
阅读 6.7k
2 个回答

我在 codesandbox 的 router-playground 试了一下,并没有发现你所提及的问题,能不能多给一些描述或者代码?

history.location 是可变对象
改变路由后 应在 接受新的 props 打印,而不是在点击的时候打印

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题