【发布时间】:2019-07-27 21:49:10
【问题描述】:
我对 React 和 Redux 比较陌生,但我对 action+store+reducer 如何实现单向数据流有基本的了解。
我在编写实际应用程序时遇到的一个问题是如何针对每个唯一错误仅显示一次错误警报。
我提出的解决方案效果很好,但我觉得它不应该是必需的,或者由于我缺乏经验,我可能会遗漏一些东西。
基本上可以归结为:
/* 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 react-native redux error-handling notifications