如何从状态访问React中状态内的另一个键

时间:2018-12-10 12:16:00

标签: javascript reactjs

我尝试学习React,但遇到了问题。我想在本教程中自己做一个例子。

import React, { Component } from 'react';

class MyComponent extends Component {
  state = {
    persons: [],
    firstPersons: 5,
    variables: {
      Id: '1',
      first: this.firstPersons,
      input: {},
    }
  }

  render() {
    console.log('this.state', this.state);
    return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;

我将渲染方法设置为console.log(this.state)

我的页面中有一个简单的状态,当我运行项目时,我收到错误消息:

Uncaught TypeError: Cannot read property 'firstPersons' of undefined

请有人告诉我我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:0)

您无法在JS中访问对象本身。您应该这样做:

import React, { Component } from 'react';

var myVar = 5;

class MyComponent extends Component {
  state = {
    persons: [],
    firstPersons: myVar,
    variables: {
      Id: '1',
      first: myVar,
      input: {},
    }
  }

  render() {
    console.log('this.state', this.state);
    return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;

import React, { Component } from 'react';

class MyComponent extends Component {
  state = {
    persons: [],
    firstPersons: 5,
    variables: {
      Id: '1',
      input: {},
    }
  }

  componentWillMount() {
    this.state.variables.first = this.state.firstPersons;
    this.setState(this.state);
  }

  render() {
    console.log('this.state', this.state);
    return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;

或者不赞成componentWillMount()

import React, { Component } from 'react';

class MyComponent extends Component {
  state = {
    persons: [],
    firstPersons: 5,
    variables: {
      Id: '1',
      input: {},
    }
  }

  static getDerivedStateFromProps(props, state) {
    this.state.variables.first = this.state.firstPersons;
    this.setState(this.state);
  }


  render() {
    console.log('this.state', this.state);
    return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;

答案 1 :(得分:-1)

我建议您使用这种语法:

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor() {
    super();
    this.state = {
     persons: [],
     firstPersons: 5,
     variables: {
     Id: '1',
       first: this.firstPersons,
       input: {},
     }
  }

  render() {
   console.log('this.state', this.state);
   return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;