根据URL反应组件状态

时间:2019-06-25 09:36:22

标签: javascript reactjs

我有一个大型网站,在主要网站下有很多子网站。我有一个SubNav,其中显示了我们当前正在访问的公司页面的名称。当用户在页面之间导航时,应使用名称更新SubNav

这是我尝试过的方法,但无济于事。

主要父级根组件。

class AppRouter extends React.Component {
  state = { companySelected: "Main Company" };

   // this should update the company and name the SubNav bar 
  updateSelectedCompany = companySelected => {
    console.log("updated selected", companySelected);
    this.setState({ companySelected: companySelected });
  };

  render() {
    return (
      <Router history={history}>
        <div>
          <NavBar />
          <SubNav companySelected={this.state.companySelected} />
          <Switch>
            <Route path="/" component={LandingPage} exact={true} />
            <Route
              path="/company/1"
              component={SubCompany1}
              exact={true}
              updateSelectedCompny={this.companySelected}
            />
            <Route
              path="/company/2"
              component={SubCompany2}
              exact={true}
            />
          </Switch>
          <Footer />
        </div>
      </Router>
    );
  }
}

SubCompany1页面如下:

class SubCompany1 extends React.Component {
  componentDidMount() {
    this.setState({ companySelected: "Sub Company 1" });
    console.log("Did Mount Sub Company1");
  }

  render() {
    return (
      <div>
        <h1>Sub Company 1</h1>
      </div>
    );
  }
}

每次访问页面都可以通过吗?我是一个非常新的反应者,并不完全确定在组件之间传递状态的最佳方法。

2 个答案:

答案 0 :(得分:2)

您需要componentDidMount()shouldComponentUpdate()

AppRouter

class AppRouter extends React.Component {
  state = { companySelected: "Main Company" };

  updateSelectedCompany = companySelected => {
    this.setState({ companySelected: companySelected });
  };

  //if condition evaluates to true, component will update and re-render. if false, no re-render.
  shouldComponentUpdate(nextProps, nextState){
     return this.state.companySelected !== nextState.companySelected
  }

  render() {
    return (
      <Router history={history}>
        <div>
          <NavBar />
          <SubNav companySelected={this.state.companySelected} />
          <Switch>
            <Route path="/" component={LandingPage} exact={true} />
            <Route
              path="/company/1"
              component={() => <SubCompany1 updateSelectedCompany={this.updateSelectedCompany} />}
          </Switch>
          <Footer />
        </div>
      </Router>
    );
  }
}

子页面

class SubCompany1 extends React.Component {
  componentDidMount() {
      this.props.updateSelectedCompany("Sub Company 1");
  }

  render() {
    return (
      <div>
        <h1>Sub Company 1</h1>
      </div>
    );
  }
}

答案 1 :(得分:1)

您应该将函数updateSelectedCompany传递给子组件

<Route
  exact={true}
  path="/company/1"
  component={() => <SubCompany1 updateSelectedCompany={this.updateSelectedCompany} />}
/>

然后在此处调用它,它将更改AppRouter组件内部的状态

componentDidMount() {
  this.props.updateSelectedCompany("Sub Company 1");
}