【发布时间】:2016-03-11 04:20:47
【问题描述】:
我正在尝试将错误捕获添加到组件的渲染功能中。当我在实际渲染函数中抛出错误时,这可以正常工作,但是如果组件的子组件中有错误,则 try 不会捕获错误(或者它们被子组件错误处理程序拦截,我不确定?)
有没有办法将错误强加给父级。
const SimpleComponent = React.createClass({
render: function(){
try{
throw 'new error'
return <div>{this.props.children}</div>
}catch(e){
console.log('error', e);
}
}
})
以上工作
const SimpleComponent = React.createClass({
render: function(){
try{
return <div>{this.props.children}</div>
}catch(e){
console.log('error', e);
}
}
})
const ChildComponent = React.createClass({
render: function(){
throw 'child error'
}
})
<SimpleComponent>
<ChildComponent />
</SimpleComponent>
上面这个不明白
【问题讨论】:
-
我不认为这就是
render()的工作原理。你真的应该避免使用任何render()方法。任何可能抛出的工作都应该存在于其他地方。 -
您应该使用 Prop Validation (PropTypes) 来确保组件正确呈现,您的示例不是 try catch 的正确用例 - 尝试并坚持 React 的内置实现
-
"你真的应该避免抛出任何 render()" => 可能已经有来自其他地方的组件可能会抛出
-
你描述了我的确切问题