reactjs - 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
};
}
解决方案
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
})
})
推荐阅读
- javascript - 您如何判断 HTML5 视频是实时流还是仅来自 Javascript 的视频?
- mongodb - 在保留根字段的同时对子文档进行分组/计数
- testing - SonarQube 不显示 Ruby on Rails 项目的测试代码覆盖率
- jquery - 带有动画的jquery循环,如何等到下一个查询
- python - 在 tkinter 应用程序中将图像添加到按钮的问题
- ruby - 没有文件扩展名的 Ruby Dir.glob 输出
- ios - viewController 的标准方法不叫 Swift
- c++ - 三元运算符的这种解释有效吗?
- relational-database - 查找所有仅提供 30 岁以上人士食用的比萨饼的比萨饼店
- facebook - Facebook Messenger Bot 通用模板重定向到“观看”部分