ภายในส่วนเล็กๆ ของแอปพลิเคชัน React/Redux/ReactRouterV4 ของฉัน ฉันมีลำดับชั้นของส่วนประกอบดังต่อไปนี้
- Exhibit (Parent)
-- ExhibitOne
-- ExhibitTwo
-- ExhibitThree
ภายในรายการย่อยของ Exhibit มีเส้นทางที่เป็นไปได้ที่แตกต่างกันประมาณ 6 เส้นทางที่สามารถแสดงผลได้เช่นกัน ไม่ต้องกังวล ฉันจะอธิบายด้วยโค้ดบางส่วน
นี่คือองค์ประกอบการจัดแสดงหลักของฉัน:
export class Exhibit extends Component {
render() {
const { match, backgroundImage } = this.props
return (
<div className="exhibit">
<Header />
<SecondaryHeader />
<div className="journey"
style={{
color: 'white',
backgroundImage: `url(${backgroundImage})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center-center'
}}>
<Switch>
<Route path={`${match.url}/exhibit-one`} component={ExhibitOne} />
<Route path={`${match.url}/exhibit-two`} component={ExhibitTwo} />
<Route path={`${match.url}/exhibit-three`} component={ExhibitThree} />
<Redirect to="/" />
</Switch>
</div>
</div>
)
}
}
โดยพื้นฐานแล้ว หน้าที่ของมันก็คือการแสดงองค์ประกอบย่อยของการจัดแสดง และตั้งค่าภาพพื้นหลัง
นี่คือหนึ่งในองค์ประกอบย่อย ExhibitOne:
export default class ExhibitOne extends Component {
constructor(props) {
super(props)
}
render() {
const { match } = this.props
return (
<div className="exhibit-one">
<Switch>
<Route path={`${match.url}/wall-one`} component={ExhibitHOC(WallOne)} />
<Route path={`${match.url}/wall-two`} component={ExhibitHOC(WallTwo)} />
<Route path={`${match.url}/wall-three`} component={ExhibitHOC(WallThree)} />
<Route path={`${match.url}/wall-four`} component={ExhibitHOC(WallFour)} />
<Route path={`${match.url}/wall-five`} component={ExhibitHOC(WallFive)} />
<Route path={`${match.url}/wall-six`} component={ExhibitHOC(WallSix)} />
</Switch>
</div>
)
}
}
เพื่อลดการพิมพ์ ฉันจึงตัดสินใจรวมส่วนประกอบต่างๆ ไว้ในองค์ประกอบลำดับที่สูงกว่า ซึ่งมีวัตถุประสงค์เพื่อส่งการดำเนินการที่จะตั้งค่าภาพพื้นหลังที่เหมาะสมในองค์ประกอบหลัก Exhibit ระดับบนสุด
นี่คือองค์ประกอบลำดับที่สูงกว่า:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions/wall-background-image'
export default function(ComposedComponent) {
class ExhibitHoc extends Component {
componentDidMount = () => this.props.setBackgroundImage(`./img/exhibit-one/${this.getWall()}/bg.jpg`)
getWall = () => {
// this part isnt important. it is a function that determines what wall I am on, in order to set
// the proper image.
}
render() {
return <ComposedComponent />
}
}
return connect(null, actions)(ExhibitHoc);
}
ในการโหลด ExhibitOne ครั้งแรก ฉันเห็นว่าผู้สร้างแอ็กชัน setBackgroundImage ดำเนินการสองครั้งโดยดูที่ Redux Logger ในคอนโซล ความโน้มเอียงเริ่มแรกของฉันที่จะใช้componentDidMountเป็นเพราะฉันคิดว่าการใช้มันจะจำกัดผู้สร้างแอคชั่นให้ดำเนินการเพียงครั้งเดียว นี่คือภาพหน้าจอของบันทึก:
ฉันคิดว่าฉันอาจเข้าใจผิดว่า Higher Order Components ทำงานอย่างไร หรืออาจเป็น React Router V4 บางประเภท อย่างไรก็ตาม ความช่วยเหลือใดๆ จะได้รับการชื่นชมอย่างมากว่าทำไมการดำเนินการนี้ถึงสองครั้ง