Javascript 反应组件在window.location更改时不重新渲染

Javascript 反应组件在window.location更改时不重新渲染,javascript,reactjs,redux,react-redux,react-router,Javascript,Reactjs,Redux,React Redux,React Router,所以,我有一个主菜单的react组件 它是指向不同页面的react router列表。每个链接都会检查窗口.location.path以确定它是否是活动页面,以便活动菜单项可以以不同方式呈现 import React, { Component } from "react"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import List from "@material-ui/c

所以,我有一个主菜单的react组件

它是指向不同页面的react router
列表。每个链接都会检查
窗口.location.path
以确定它是否是活动页面,以便活动菜单项可以以不同方式呈现

import React, { Component } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import List from "@material-ui/core/List";

class MainMenu extends Component {
  render() {
    return (
      <List>
        <Link to="/products" className={window.location.pathname === "/products" ? "active" : null }>Products</Link>
        <Link to="/sales" className={window.location.pathname === "/sales" ? "active" : null }>Sales</Link>
      </List>
    )
  }
}
我仍然不确定此问题是否与connect有关,或者connect是否只是突出显示了使用
window.location.pathname
时出现的问题,react不知道何时更新


非常感谢您的帮助

更改window.location.pathname时,React组件不会重新加载。只有状态更改才会导致组件重新加载。您需要侦听window.pathname更改并将其映射到状态,然后只有您的组件将重新加载

对于这些事情,你可以看看react路由器。将它添加到您的项目中,这样的事情很容易实现

视图的此状态发生任何更改时,视图将更改 组成部分。我建议你听听window.location的变化

这是密码

constructor(){
   this.state = {currentPath:window.location.pathname}

   window.onbeforeunload = function(e) {
      this.setState({currentPath:window.location.pathname})
   };
}
和在render()中

render(){
返回(
产品
销售额
)
}

谢谢Shubham,我想可能是这样的,所以我想知道为什么它没有连接功能也能工作谢谢这是一个很好的解决方案。不确定页面是否“卸载”,因为我使用的浏览器路由器实际上没有重新加载页面是的,但我在mozilla文档中看到,每当windw.location.path发生更改时,就会触发此特定事件。我不知道它是否有效。你能告诉我这是否有效吗:)虽然这可能解决OP的问题,但这是徒劳的。正如所料,React路由器有一个名为
的组件,专门用于解决OP的实际问题。quote:“的一个特殊版本,它将在呈现元素与当前URL匹配时向呈现元素添加样式属性。”
constructor(){
   this.state = {currentPath:window.location.pathname}

   window.onbeforeunload = function(e) {
      this.setState({currentPath:window.location.pathname})
   };
}
render() {
    return (
      <List>
        <Link to="/products" className={this.state.currentPath === "/products" ? "active" : null }>Products</Link>
        <Link to="/sales" className={this.state.currentPath === "/sales" ? "active" : null }>Sales</Link>
      </List>
    )
  }