【问题标题】:How To Get State of Switch If No Match in React ReactRouter如果在 React React Router 中不匹配,如何获取 Switch 的状态
【发布时间】:2018-01-03 03:42:34
【问题描述】:

我正在使用 ReactRouter 并且想要在 RouteNotFound 组件被命中时执行一些设置状态(最后一个表示没有其他匹配)。

我的this.handler 做了一个 setState 以便我知道它被调用了。这当然会给我一个错误,说“无法在现有状态转换期间更新,例如在渲染中”。

有没有一种方法可以设置我的状态来告诉我哪个(我真的想知道最后一个)switch 语句被执行?

render() {
    return (
        <div>
            <Switch>
                <Route exact path="/" component={Home}/>
                <Route exact path="/p1" component={p1}/>
                <Route exact path="/p2" component={p2}/>
                <RouteNotFound action={this.handler} ></RouteNotFound>
            </Switch>
        </div>
    );
}

【问题讨论】:

  • 您正在寻找的是 react-router 的 onEnter 功能,在 react-router-v4 中可以通过生命周期方法来实现。检查重复的问题以进行实施

标签: reactjs react-router


【解决方案1】:

我们开始吧:

not-found.js:

import React from 'react';
import { Route } from 'react-router-dom';

const RouteNoteFound = ({ action }) => (
  <Route
    render={props => (
      <NotFoundPageComponent action={action} />
    )}
  />
);


export default RouteNoteFound;

class NotFoundPageComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    this.props.action()
  }

  render() {
    return (
      <div>404 not found</div>
    )
  }
}

index.js 中:

handler = () => {
    alert("alert from app.js but run in not found page")
}

render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={Page} />
          <Route path="/page" component={Page} />
          <RouteNoteFound action={this.handler} />
        </Switch>
      </BrowserRouter>
    );
}

这里是堆栈闪电战中的DEMO

【讨论】:

  • 在 index.js 中,我想将该“状态”推送到其父级,然后再推送到其父级。我想我想在动作处理程序中设置状态,然后在 ComponentDidUpdate 中,将状态发送给父级。当我这样做时,我会遇到递归问题。
【解决方案2】:

试试这个。

像这样定义未找到的路由:

<Route render={props => <RouteNotFound action={this.handler} />}></Route>

因为,根据 Doc

没有 path 属性的 &lt;Route&gt; 或没有 from 属性的 &lt;Redirect&gt; 将 始终匹配当前位置。

检查 Doc example 是否有“无路径匹配”。

现在在 RouteNotFound 组件中使用 componentDidMount 生命周期方法,每当 RouteNotFound 将被渲染时,componentDidMount 将被调用。从componentDidMount调用父函数,像这样:

componentDidMount(){
   this.props.action();
}

现在在父组件的action 内设置状态。

【讨论】:

  • {this.handler} 中仍然存在问题。我收集我无法在渲染函数中进行状态更新。警告:在现有状态转换期间无法更新(例如在render 或其他组件的构造函数中)。渲染方法应该是 props 和 state 的纯函数;构造函数副作用是一种反模式,但可以移动到componentWillMount
  • 您期望 {this.handler} 中有什么。我有 setState(...) 导致我在上一条评论中列出的错误
  • 不确定,为什么会抛出错误,您是否使用 ()this.handler ?因为它应该工作。在componentWillMount 中执行 setState 时它正在工作?
猜你喜欢
  • 2023-03-29
  • 2017-09-11
  • 2019-08-23
  • 2016-02-04
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 2020-08-29
  • 2020-11-05
相关资源
最近更新 更多