gpt4 book ai didi

reactjs - 错误边界禁用交换机内部的路由

转载 作者:行者123 更新时间:2023-12-03 07:38:15 26 4
gpt4 key购买 nike

对于 a long time,在遇到错误边界后,我一直试图让路由在我们的应用程序中工作,但直到今天我才发现看似与周围许多示例相同的代码有一个重要区别:路由被包裹一个 Switch 。如果启用,这个简单的更改足以阻止路由工作。 Demo

采取以下代码段。如果我删除 Switch 位,即使每个组件都应该失败,这也可以正常工作,但如果被开关包裹则不会。我想知道为什么。

<div style={{ backgroundColor: "#ffc993", height: "150px" }}>
<Switch>
<Route
path="/"
exact
render={() => (
<ErrorBoundary>
<MyComponent1 title="Component 1" />
</ErrorBoundary>
)}
/>
<Route
path="/comp1"
render={() => (
<ErrorBoundary>
<MyComponent1 title="Component 1 Again" />
</ErrorBoundary>
)}
/>
<Route
path="/comp2"
render={() => (
<ErrorBoundary>
<MyComponent2 title="Component 2" />
</ErrorBoundary>
)}
/>
</Switch>

最佳答案

基本上,这个问题归结为 React 如何 reconciliation .

When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element



假设我们有这个示例应用程序:
<App>
<Switch>
<Route path="a" component={Foo}/>
<Route path="b" component={Foo}/>
</Switch>
</App>

有点不直观,这将重用 Foo 的相同实例。两条路线!一个 <Switch>将始终返回第一个匹配的元素,所以基本上当 React 渲染时,这相当于树 <App><Foo/></App>对于路径“a”和 <App><Foo/></App>对于路径“b”。如果 Foo 是一个有状态的组件,这意味着状态会被保留,因为该实例只是传递了新的 props (在我们的例子中,除了 children 之外,没有任何 props),并且期望通过重新计算它自己的来处理这个状态。

由于我们的错误边界正在被重用,虽然它的状态无法更改,但它永远不会重新渲染其父路由的新子路由。

React 为此隐藏了一个技巧,我只在其博客上看到过明确记录:

In order to reset the value when moving to a different item (as in our password manager scenario), we can use the special React attribute called key. When a key changes, React will create a new component instance rather than update the current one. (...) In most cases, this is the best way to handle state that needs to be reset.



一个有点 related issue on Brian Vaughn's error bondary package 的人第一次向我暗示了这一点。 :

The way I would recommend resetting this error boundary (if you really want to blow away the error) would be to just clear it out using a new key value. (...) This will tell React to throw out the previous instance (with its error state) and replace it with a new instance.



使用 key 的替代方法s 将实现暴露一些可以在外部调用的钩子(Hook)或尝试检查 children改变属性(property),这很难。像这样的东西可以工作( demo):
componentDidUpdate(prevProps, prevState, snapshot) {
const childNow = React.Children.only(this.props.children);
const childPrev = React.Children.only(prevProps.children);

if (childNow !== childPrev) {
this.setState({ errorInfo: null });
}

但它的工作量更大,而且更容易出错,所以为什么要麻烦:坚持添加 key Prop :-)

关于reactjs - 错误边界禁用交换机内部的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59056211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com