我正在使用React Redux应用程序,我对某种最佳实践有一个非常基本的问题。
我有MainComponent(一种容器),在其中我要在componentDidMount上获取数据:
class MainComponent extends React.Component {
componentDidMount(){
this.fetchData()
}
fetchData() {
this.props.fetchDataAction()
}
render() {
return (
<div>
<ChildComponent1 />
<ChildComponent2 />
</div>
)
}
}
export default connect(mapStateToProps,{fetchDataAction})(MainComponent)
如何将获取的数据传递给ChildComponents?最佳实践是什么?有两种可能的解决方案(恕我直言-也许更多?)
第一个解决方案:
class MainComponent extends React.Component {
...
render() {
return (
<div>
<ChildComponent1 dataOne={this.props.data.one} />
<ChildComponent2 dataTwo={this.props.data.two} />
</div>
)
}
...
第二种解决方案-将ChildComponents连接到要存储的组件,该组件由MainComponent中的fetchDataAction()更新:
class ChildComponent1 extends React.Component {
render() {
return (
<div>
{this.props.one}
</div>
)
}
}
function mapStateToProps(state){
return (
one: state.one
)
}
export default connect(mapStateToProps,null)(ChildComponent1)
现在,当ChildComponents不触发可更新存储的操作时,我将使用第一个解决方案;而当第二个解决方案执行时,我将使用第二个解决方案。但是我不确定这是否合适。
最佳答案
如果您有多个子组件,则必须将一部分获取的数据传递给不同的子组件;我建议保留父组件作为单源。
您可以尝试类似:
class MainComponent extends React.Component {
constructor(){
super()
this.state = {
data : {}
}
}
componentDidMount(){
this.fetchData()
}
fetchData() {
this.props.fetchDataAction()
}
componentWillReceiveProps(nextProps){
//once your data is fetched your nextProps would be updated
if(nextProps.data != this.props.data && nextProps.data.length>0){
//sets your state with you data--> render is called again
this.setState({data:nextProps.data})
}
render() {
//return null if not data
if(this.state.data.length === 0){
return null
}
return (
// it should have keys as one and two in api response
<div>
<ChildComponent1 data={data.one}/>
<ChildComponent2 data={data.two}/>
</div>
)
}
}
function mapStateToProps(state){
return (
data: state
)
}
export default connect(mapStateToProps,{fetchDataAction})(MainComponent)
我觉得所有逻辑都以此方式停留在一个地方。假设您打算将来增加一些子组件,则只需在上面添加一行代码,并在API中进行少量更改即可。但是,如果您阅读了每个组件,则必须再次连接该组件以进行存储,这使其变得更加复杂。
因此,如果除了获得
data
之外,子组件中没有任何其他逻辑,我会将此逻辑保留在父组件中。