我对React和Redux相对较新,但是我对action + store + reducers如何工作以实现单向数据流有基本的了解。
在编写实际应用程序时遇到的一个问题是,如何针对每个唯一错误仅一次显示错误警报。
我想出的解决方案效果很好,但是我觉得不应该这样做,或者由于我的经验不足,我可能会缺少一些东西。
本质上可以归结为:
/* In the reducer: */
const initialState = {
someStateData: 'wow state',
error: undefined,
errorId: 0,
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case SUCCESS:
return {
...state,
someStateData: action.data,
error: undefined,
}
case ERROR:
return {
...state,
error: action.error,
errorId: state.errorId + 1,
}
default:
return state
}
}
/* In the view component: */
class SomeComponent extends Component {
constructor(props) {
super(props)
this.state = {
lastErrorId: 0,
}
}
processHandlers() {
if (this.props.error &&
this.props.lastErrorId !== this.state.lastErrorId) {
this.props.onFailure?.(this.props.error)
this.setState({
...this.state,
lastErrorId: this.props.lastErrorId,
})
}
}
componentDidMount() {
this.processHandlers()
}
componentDidUpdate(prevProps, prevState) {
this.processHandlers()
}
}
const mapStateToProps = state => {
return {
error: state.error,
lastErrorId: state.errorId,
}
}
export default (connect(mapStateToProps)(SomeComponent))
这很好用-还有另外一种更好的方法吗? Redux更惯用吗?
最佳答案
将其添加到您的逻辑或体系结构中...一旦发生错误,将其保存,这可能是商店中跟踪错误和其他当前问题的另一部分。这就是状态管理的要点,您的应用程序中正在发生的事情...
关于reactjs - 如何防止Redux多次显示同一错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57236324/