渲染组件及其状态

时间:2018-05-11 11:15:40

标签: javascript reactjs

我现在对生命周期钩子感到困惑。这是我的代码:

App.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>
    );
  }
}
&#13;
&#13;
&#13;

Component.js:

&#13;
&#13;
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>
        )
    }
}
&#13;
&#13;
&#13;

所以我想做的是组件呈现自己,这取决于它们从App.js得到的数组。但是如何在渲染发生之前设置状态?我可以以某种方式要求组件再次渲染,如果它确实挂载?还是其他任何解决方案?

2 个答案:

答案 0 :(得分:1)

您只需在构造函数本身中分配this.props.componentsComponents

constructor(props){
            super(props);
            this.state={
                componentsComponents: this.props.componentsComponents||[]
            }
        }

答案 1 :(得分:0)

将过滤器带到应用程序

这里看起来你没有调用renderComponents,而且你也试图在其自身内部渲染一个Component,这很难说明。将renderComponents函数添加到App,并使用App内部的Component渲染数据,并简单地将props传递给无状态Component,这可能是表示数据的更简单的解决方案。

如果递归调用确实是表示此数据的最佳方式,则可能需要使用getDerivedStateFromProps在更新时将props移动到状态,如果您希望将该数据存储在状态中 - 例如:

static getDerivedStateFromProps(nextProps) {
  return {
    componentsComponents: nextProps.componentsComponents
  }
}

添加到组件。