componentDidMount()不是设置值

时间:2018-03-12 09:10:19

标签: javascript json reactjs react-redux fetch

我正在重构我的代码,我正在尝试使用所有可用的生命周期方法。我试图使用componentDidMount()初始化组件的状态。之前,我每次尝试使用父组件中的属性时都使用this.props(并且直到代码变大为止),现在我尝试使用this.state,以便在每次更改后自动重新呈现。有人能告诉我哪里错了吗?

这是App.js的代码:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import logo from './logo.svg';
import './App.css';
import BasicLayout from './newtask2/BasicLayout2';
import fetch from 'cross-fetch';

class App extends React.Component{

  constructor(props){
    super(props);
    this.state = {
       portletlocations: [],
       portlets: []
    }
  }

  loadPortletLocationsFromServer() {
    var self = this;
     try {
        fetch("http://localhost:8080/portletlocation/all", {
          headers : { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          }
        }).then( (response) => {
          return response.json();
        }).then((json) => {
          console.log("Loaded from server", json);
          self.setState({portletlocations: json});
        })
      } catch (err) {
        console.error(err);
      } 
   }

  loadPortletsFromServer(){
    var self = this;
    try{
      fetch("http://localhost:8080/portlet/all", {

      }).then( (response) => {
        return response.json();
      }).then((json) => {
        console.log("Loaded from server", json);
        self.setState({portlets: json});
      })
    } catch (err) {
      console.error(err);
    }
  }

  componentDidMount() {
    this.loadPortletLocationsFromServer();
    this.loadPortletsFromServer();
  }

  render() {
    return ( <BasicLayout portletlocations={this.state.portletlocations} portlets = {this.state.portlets} /> );
  }
 }

 export default App;

这是BasicLayout代码的一部分:

class BasicLayout extends React.PureComponent {

  constructor(props){
    super(props);
    this.state = { 
      open: false,
      portletlocations: [],
      portlets: []
    };
  }

  componentDidMount(){
    this.setState({
      portletlocations: this.props.portletlocations,
      portlets: this.props.portlets
    });
  }


  render() {
    if(this.state.portletlocations != undefined){
      console.log("portletlocations=", this.state.portletlocations); //here I get and empty array

1 个答案:

答案 0 :(得分:0)

这些道具可能尚未被组件使用,因为它们(从您提供的代码中)出现以异步加载。

如果是这样,您应该将逻辑从componentDidMount()移到componentWillReceiveProps()

这样的事情应该有效:

componentWillReceiveProps(nextProps){
  if(nextProps.portletlocations || nextProps.portlets)
    this.setState({
      portletlocations: nextProps.portletlocations,
      portlets: nextProps.portlets
  });
}