จะป้องกันการแสดงข้อผิดพลาดเดียวกันหลายครั้งด้วย Redux ได้อย่างไร

ฉันค่อนข้างใหม่กับ React และ Redux แต่ฉันมีความเข้าใจพื้นฐานเกี่ยวกับวิธีการทำงานของ actions+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 หรือไม่?


person Nathan Bergeron    schedule 27.07.2019    source แหล่งที่มา


คำตอบ (1)


เพิ่มลงในตรรกะหรือสถาปัตยกรรมของคุณ...เมื่อเกิดข้อผิดพลาด ให้บันทึกไว้ นั่นอาจเป็นอีกส่วนหนึ่งของร้านค้าของคุณที่คอยติดตามข้อผิดพลาดและปัญหาปัจจุบันอื่นๆ นั่นคือประเด็นของการจัดการของรัฐ สิ่งที่เกิดขึ้นในใบสมัครของคุณตอนนี้...

person user998548    schedule 27.07.2019