ฉันค่อนข้างใหม่กับ 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 หรือไม่?