首页 > 解决方案 > reactjs中的状态没有改变

问题描述

我正在尝试根据错误请求更新状态。最初我将其设置为 false,一旦出错,我将其更新为 true。但我总是认为它是错误的。有人可以帮我解决这个问题。谢谢。

下面是代码片段,

class Component extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            error: false,
        };
    }
    submit = () => {
        function_1.finally(() => {
          ............
        }).catch((request) => {
            const errors = request.response.errors;
            let err1;
            if (errors) {
                err1 = errors.find(
                    e => e.code === 'error_code');
            }
            if (err1) {
               this.setState({
                        error: true,
                    });
            }  else {
                this.setState({error: false});
            }

        });
    };
    };
    render = () => {
        const { error } = this.state;
        console.log("error in render", error); //this is always false
    };
}

标签: reactjs

解决方案


catch 块接受error参数而不是通过 访问request.response.errors,试试这样:

.catch((error) => {
   const errorStatus = Boolean(error.find(e => e.code === 'error_code'))
   this.setState({
    error: errorStatus
   })
})

但我想,catch 块仅在捕获错误后运行,那么为什么不简单地将错误状态设置为 true 而不是检查 error_code 呢?

.catch(() => {
   this.setState({
    error: true
   })
})

推荐阅读