【问题标题】:How to prevent showing the same error multiple times with Redux?如何防止使用 Redux 多次显示相同的错误?
【发布时间】: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


    【解决方案1】:

    将其添加到您的逻辑或架构中...一旦发生错误,请保存它,这可能是您商店的另一部分,用于跟踪错误和其他当前问题。这就是状态管理的重点,你的应用程序现在正在发生什么......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 2021-03-25
      相关资源
      最近更新 更多