我有许多React组件需要获取要显示的某些项目。除了非常简单的componentDidMount
回调之外,组件可以是功能组件。有没有一个好的设计模式可以让我回归功能组件?
class Things extends React.Component {
componentDidMount() {
this.props.fetchThings()
}
render() {
things = this.props.things
...
}
}
我正在使用react-redux,我还使用connect
将我的组件连接到我的reducer和actions。这是该文件:
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)
答案 0 :(得分:1)
功能组件是指不做 任何的组件。你只要给他们道具,他们渲染。实际上,如果您的组件需要提取任何内容,那么您的组件可能会转换为answer来获取所需的数据。然后,您可以将组件的UI部分抽象为容器呈现的一个或多个纯功能组件,方法是将其获取的数据作为道具传递。
我认为演示文稿/容器组件拆分是你在这里寻找的模式。