简体   繁体   English

如何在React JS中处理状态错误?

[英]How can I handle errors in state in React JS?

In my stores, I have functions set to handle errors in API calls. 在我的商店中,我设置了处理API调用错误的函数。

One example is for authorization - if a user cannot view a project , they get an unauthorized error. 一个例子是授权 - 如果用户无法查看project ,他们会收到未经授权的错误。

In my store, I set an error property on the state. 在我的商店中,我在状态上设置了一个error属性。

Then, in my component's render function, I first check for this.state.error . 然后,在我的组件的渲染函数中,我首先检查this.state.error This works fine - I render a reused error component containing the error message and code. 这很好 - 我渲染一个包含错误消息和代码的重用错误组件。

The problem is that I need to reset the error state to null after the user moves on - yet resetting the state causes the component to re-render. 问题是我需要在用户移动后将错误状态重置为null - 但重置状态会导致组件重新呈现。

My current approach (in my component's render function): 我目前的方法(在我的组件的渲染功能中):

if (this.state.error) {
        return (
            <Error 
                errorTitle={this.state.errorCode} 
                errorMessage={this.state.error}
                clearErrors={this.clearErrors}
            />
        )
    }

And a function that belongs to the same class: 和属于同一个类的函数:

clearErrors: function () {
    this.setState({
        error: null,
        errorCode: null
    });
},

And then my Error component: 然后我的错误组件:

var Error = React.createClass({

    clearErrors: function () {
        this.props.clearErrors();
    },

    render: function () {
        return (
            <Panel className='errorPanel' header={this.props.errorTitle} bsStyle='danger'>
                <p>{this.props.errorMessage}</p>
                <a href='#/dashboard'>
                    <Button onClick={this.clearErrors}>Return to Dashboard</Button>
                </a>
            </Panel>
        )
    }
});

The problem is evident - before the onClick actually returns my user to the dashboard, it very quickly renders the component that the user is not supposed to be able to see. 问题很明显 - 在onClick实际上将我的用户返回到仪表板之前,它会非常快速地呈现用户不应该看到的组件。

How should I be handling this? 我应该怎么处理这个?

The errorcode should not in the components state. 错误代码不应处于组件状态。 Because (apparently) it does not correspond fully with the components state. 因为(显然)它与组件状态不完全对应。 From what I gather you are looking for is the following states: 从我收集的你正在寻找的是以下状态:

  • Error code = not null: error component displayed 错误代码=非null:显示错误组件
  • Error code reset to null: error component still displayed (because you do NOT want to re-render the component) 错误代码重置为null:仍然显示错误组件(因为您不想重新呈现组件)

So I would suggest removing error from state and do something like: 所以我建议从状态中删除错误并执行以下操作:

render() {
  errorcode = this.props.errorcode;
  if (this.props.errorcode) {
    return <ErrorComponent...>
  }

clearErrors() {
  errorcode = null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM