[英]How can I handle errors in state in React JS?
在我的商店中,我設置了處理API調用錯誤的函數。
一個例子是授權 - 如果用戶無法查看project
,他們會收到未經授權的錯誤。
在我的商店中,我在狀態上設置了一個error
屬性。
然后,在我的組件的渲染函數中,我首先檢查this.state.error
。 這很好 - 我渲染一個包含錯誤消息和代碼的重用錯誤組件。
問題是我需要在用戶移動后將錯誤狀態重置為null - 但重置狀態會導致組件重新呈現。
我目前的方法(在我的組件的渲染功能中):
if (this.state.error) {
return (
<Error
errorTitle={this.state.errorCode}
errorMessage={this.state.error}
clearErrors={this.clearErrors}
/>
)
}
和屬於同一個類的函數:
clearErrors: function () {
this.setState({
error: null,
errorCode: null
});
},
然后我的錯誤組件:
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>
)
}
});
問題很明顯 - 在onClick實際上將我的用戶返回到儀表板之前,它會非常快速地呈現用戶不應該看到的組件。
我應該怎么處理這個?
錯誤代碼不應處於組件狀態。 因為(顯然)它與組件狀態不完全對應。 從我收集的你正在尋找的是以下狀態:
所以我建議從狀態中刪除錯誤並執行以下操作:
render() {
errorcode = this.props.errorcode;
if (this.props.errorcode) {
return <ErrorComponent...>
}
clearErrors() {
errorcode = null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.