首页 文章

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

提问于
浏览
0

我试着学习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;

我把渲染方法a console.log(this.state) .

我的页面中有这个简单的状态,当我运行项目时出现错误:

Uncaught TypeError: Cannot read property 'firstPersons' of undefined

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

2 回答

  • 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;
    
  • 1

    您无法在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;
    

相关问题