gpt4 book ai didi

javascript - 在react中点击链接时处理异常

转载 作者:行者123 更新时间:2023-12-02 23:03:58 24 4
gpt4 key购买 nike

我在react-table中显示了一个href链接,它调用了Spring后端应用程序。专栏示例代码

Header: '',                                                                                           
Cell: row => {
return (
<div>
<a href=/url/apicall/>>
</a>
</div>
)
}

问题是,如果 url 文件为字节流,我的问题是,如果出现异常,应用程序将重定向到常见错误页面。

我怎样才能更好地处理这个问题?我的想法是,不要直接提供 href,而是创建一个方法并在 href 中调用该方法并处理该方法中的响应。有什么建议 ?谢谢,

最佳答案

您可以使用Error boundaries react 中

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch(). Use static getDerivedStateFromError() to render a fallback UI after an error has been thrown. Use componentDidCatch() to log error information.The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters

The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters

1/ error: – The error object which was thrown

2/ info: – An object with a componentStack key contains the information about which component threw the error.

The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters

componentDidCatch(error, info)

首先您需要像这样创建 ErrorBoundaries 组件

class ErrorHandlerBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}

componentDidCatch(error, info) {
// You can also log the error to an error reporting service
errorHandlerService(error, info);
}

render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return Something went wrong.;
}

//otherwise just render child props as normally
return this.props.children;
}
}

所以我们需要像这样在错误边界组件中添加我们的组件

//Then we just need to define our component like this
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { error: true };
}

render() {
if (this.state.error) {
// Simulate a JS error
throw new Error("oops");
}
return <h1> Hello world</h1>;
}
}

然后像这样使用

<ErrorHandlerBoundary>
<MyComponent />
</ErrorHandlerBoundary>

关于javascript - 在react中点击链接时处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57672636/

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