消失的值this.state.array ReactJS

时间:2017-12-28 20:43:41

标签: javascript arrays reactjs this state

我使用以下方法获取数组:

module.exports = {
          fetchIntegrations(self) {
            var encodedURI = "OMITTED";
            axios.get(encodedURI).then(function (r) {
              self.setState({
                response: r.data,
              })
            })
            return self
          }
        };

然后我用这种方法调用它:

_getIntegration(){
            var self = this;
            var axios = require("axios");
            axios.defaults.headers.common[ "Authorization"] = this.props.userInfo.isAuthorized

            api.fetchIntegrations(self);
            console.log("This " , this);
            console.log("This.state " , this.state);
            console.log("This.state.response ", this.state.response);

return this.state.response.map((integration) => {
    return (<NavBarItem key={integration.identifier}
             name={integration.displayName}/>);
            });
         }

这是NavBarItem类:

class NavBarItem extends React.Component {
  render() {
    return(
    <div className="navbaritem">                
            <Text className="navbaritem-name">{this.props.name}</Text>
            </div>
    );
  }
}

_getIntegration方法位于此Layout类(删节)中:

export class Layout extends React.Component {
constructor (props) {
    super(props)
this.state = {
        response: [],
      }
  }


componentDidMount = () => {
      this._getIntegration();
  }
}

当它在控​​制台中被记录时,它的项目中包含我的响应数组。在this.state和this.state.response中,响应数组以某种方式包含0个项目。我尝试在几个不同的地方使用setState()而没有运气。关于如何访问我的响应数组值的想法?我的目标是为数组中的每个对象创建NavBarItems,但是由于我的响应数组中没有项目,所以没有太多发生:( 谢谢!!

1 个答案:

答案 0 :(得分:0)

您应该重新构造代码,以便fetchIntegrations服务返回一个带有数据的promise,返回到Layout组件。您可以将console.log置于以下任何功能中:shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate如果您想在每个阶段查看组件的状态。

我在CodeSandbox上发布了一个示例:https://codesandbox.io/s/lrvzm872v9

主要部分是Layout组件和fetchIntegration服务:

class Layout extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      response: [],
    }
  }

  componentDidMount() {
    fetchIntegrations().then((data) => {
      this.setState({
        response: data
      })
    })
  }

  getIntegrations() {
    const integrations =this.state.response.map((integration) => {
      return (
        <NavBarItem key={integration.identifier}
          name={integration.displayName} />
      )
    });
    return integrations;
  }
  render() {
    if (this.state.response.length == 0) { return null; }
    const integrations = this.getIntegrations();
    return (
      <nav>
      { integrations }
      </nav>
    )
  }
}

fetchIntegration:

function fetchIntegration(){
   var encodedURI = "OMITTED";
   return axios.get(encodedURI).then(function (r) {
          return r.data;
    }
}