![](/img/trans.png)
[英]Fetching String from an input text field in Flux design pattern in JSX/React
[英]React design pattern for fetching items
我有許多React組件,需要獲取某些項目才能顯示。 這些組件可以是功能組件,但非常簡單的componentDidMount
回調除外。 是否有一個好的設計模式可以讓我返回到功能組件?
class Things extends React.Component {
componentDidMount() {
this.props.fetchThings()
}
render() {
things = this.props.things
...
}
}
我正在使用react-redux,也正在使用connect
將組件連接到我的reducer和action。 這是該文件:
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)
功能組件意味着是什么都不做組件。 您只要給他們道具就可以了。 實際上,如果您的組件根本不需要獲取任何內容,則很可能應該將您的組件轉換為一個容器 ,以獲取所需的數據。 然后,您可以通過傳遞作為道具的數據,將組件的UI部分抽象為一個或多個純功能組件,容器將這些組件呈現出來。
我相信演示文稿/容器組件的拆分是您在此處尋找的模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.