【问题标题】:state' is not defined no-undefstate' 未定义 no-undef
【发布时间】:2022-01-26 06:38:10
【问题描述】:

所以我正在学习 React 课程,但我不知道如何解决这个问题。 它建议我将展开运算符“...”而不是“this”。从数组中选择元素。但是当我这样做时,它仍然显示错误'状态'未定义 no-undef'。我是 React 新手,我在这里做错了吗?

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import { render } from '@testing-library/react';
import React from 'react';
import { Component } from 'react/cjs/react.production.min';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    persons: [{name: 'Max', age: 22},
              {name: 'Manu', age: 19},
              {name: 'Stephanie', age: 41},
              {name: 'George', age: 40}
            ]
    
  }

  render() {
  return (
    <div className="App">
     <h1>Hi, I am a React App</h1>
    <p>This is really working!</p>
    <button>Switch Name</button>
    <Person name= {this.state.persons[0].name} {this.state.persons[0].age}/>
    <Person {this.persons[1].name} {this.state.persons[1].age}/>
    <Person {this.state.persons[2].name} {this.state.persons[2].age}> My Hobbie is swimming.</Person>
    <Person {this.state.persons[3].name} {this.state.persons[3].age}/>
    </div>
  );
}
}


export default App;

【问题讨论】:

  • 我认为你正在尝试做{...this.state.persons[0]}

标签: javascript html reactjs jsx


【解决方案1】:

假设&lt;Person /&gt; 组件接受agename 属性,您可以使用以下传播语法将具有匹配属性的整个对象传播到该组件:

&lt;Person {...{this.persons[0]}} /&gt;

上面是等价的但简写

&lt;Person name={this.persons[0].name} age={this.persons[0].age} /&gt;

还请注意您插入的语法错误:

&lt;Person name= {this.state.persons[0].name} {this.state.persons[0].age}/&gt;

首先,空格不应该在那里,因为您需要将值传递给给定的属性,这与可以创建带有或不带空格的变量的 vanilla JS 语法不同:

const x = 1;const x=1;

其次,您尝试将 age 值传递给组件,但您没有指出应该将其分配给哪个属性。

继续前进,祝你好运。

【讨论】:

    猜你喜欢
    • 2018-10-02
    • 2021-05-26
    • 2021-10-16
    • 2018-06-09
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多