我现在对生命周期钩子真的很困惑。这是我的代码:
应用程序.js:
class App extends Component {
constructor(props){
super(props);
this.state = {
arrayOfComponents: []
}
}
componentDidMount(){
//i get the properties from the server which responds with the database's elements
fetch('http://localhost:3001/')
.then(res => res.json())
.then(arrayOfData => this.setState({arrayOfComponents: arrayOfData}))
.catch(err => console.log(err))
}
render() {
console.log(this.state) //first returns empty array, after the mount returns the db's array of elements
return (
<div className="App">
<Component name='First' id={1} componentsComponents={this.state.arrayOfComponents} />
</div>
);
}
}
组件.js:
class Component extends React.Component{
constructor(props){
super(props);
this.state={
componentsComponents: []
}
}
//here i was tried with componentDidMount, componentWillMount to set the
//this.props.componentsComponents to this.state.componentsComponents
//but it didn't work
renderComponents = () => {
if(this.state.componentsComponents.length){
return this.state.componentsComponents.filter(c => c.inhertedFromId === this.props.id).map(c => {
return <Component name={c.name} id={c.id} componentsComponents={this.props.componentsComponents} />
})
}
}
render(){
return(
<div>
{this.renderComponents()}
</div>
)
}
}
所以我想要做的是让组件自己呈现,这取决于它们从App.js
. 但是如何在渲染发生之前设置状态?如果它确实挂载了,我可以以某种方式要求组件再次渲染吗?或者有其他解决方案吗?
在这里,您似乎没有调用 renderComponents,而且您还试图在其内部渲染一个 Component,这很难推理。将 renderComponents 函数带到 App 中,并在 App 内部使用 Component 渲染数据,并将 props 向下传递给无状态的 Component,这可能是表示数据的更简单的解决方案。
如果递归调用确实是表示此数据的最佳方式,则可能需要使用 getDerivedStateFromProps 将 props 移动到更新状态,如果您希望将该数据存储在状态中 - 类似于:
static getDerivedStateFromProps(nextProps) {
return {
componentsComponents: nextProps.componentsComponents
}
}
添加到组件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句