0
我有一些React組件需要獲取某些項目才能顯示。這些組件可以是功能組件,除非有一個非常簡單的componentDidMount
回調。有沒有一個好的設計模式可以讓我返回到功能組件?React設計模式獲取項目
class Things extends React.Component {
componentDidMount() {
this.props.fetchThings()
}
render() {
things = this.props.things
...
}
}
我使用的反應,終極版,我也用connect
到我的組件連接到我的減速器和行動。這裏是該文件:
import { connect } from 'react-redux'
import Things from './things'
import { fetchThings } from '../../actions/thing_actions'
const mapStateToProps = ({ things }) => ({
things: things,
})
const mapDispatchToProps =() => ({
fetchThings:() => fetchThings()
})
export default connect(mapStateToProps, mapDispatchToProps)(Things)
取而代之的是在這個文件中的東西是否有意義?也許是這樣的:
import { connect } from 'react-redux'
import Things from './things'
import { fetchThings } from '../../actions/thing_actions'
const mapStateToProps = ({ things }) => ({
things: things,
})
class ThingsContainer extends React.Component {
componentDidMount() {
fetchThings()
}
render() {
return (
<Things things={this.props.things} />
)
}
}
export default connect(mapStateToProps)(ThingsContainer)
感謝您的回覆。我知道容器的設計模式,但它看起來像是過度殺傷,因爲'fetchThings'實際上是該組件唯一的功能。 但這給了我一個想法。如果我使用「'connect」文件,我已經必須讓組件道具也可以獲取這些東西?我用這個想法編輯了我的問題。 –
這會使你的組件呈現和連接,當涉及到較大的組件時,這通常會被忽略,但對於小型組件來說可以。 –
真的嗎?爲什麼會皺起眉頭?我通常會看到redux的優勢,它可以讓你使用更多的功能組件,通過使用連接來爲你的reducer直接提供道具。 –