简体   繁体   English

state' 未定义 no-undef

[英]state' is not defined no-undef

So I'm following a course on React and I can't figure out how to solve this.所以我正在学习关于 React 的课程,但我不知道如何解决这个问题。 It suggests me that I put Spread operator '...' instead of 'this.'它建议我将展开运算符“...”而不是“this”。 to select elements from the array.到数组中的 select 元素。 But when I do that it still shows error 'state' is not defined no-undef'.但是当我这样做时,它仍然显示错误'状态'未定义 no-undef'。 Im new to React, so am I doing something wrong here?我是 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;

Assuming <Person /> component accepts age and name properties you can spread entire object with matching properties to this component using spread syntax as following:假设<Person />组件接受agename属性,您可以使用以下传播语法传播整个 object 与该组件的匹配属性:

<Person {...{this.persons[0]}} />

The above is equivalent yet shorthand for以上是等价的但简写为

<Person name={this.persons[0].name} age={this.persons[0].age} />

Please also note a wrong syntax you were inserting:另请注意您插入的语法错误:

<Person name= {this.state.persons[0].name} {this.state.persons[0].age}/>

First, the space shouldn't be there as you need to pass a value to a given property unlike to the vanilla JS syntax where you can create a variable with or woithout spaces:首先,空格不应该在那里,因为您需要将值传递给给定的属性,这与 vanilla JS 语法不同,您可以在其中创建带有或不带空格的变量:

const x = 1; or const x=1;const x=1;

Secondly, you are trying to pass age value to component but you haven't pointed out which property it should be assigned to.其次,您试图将age值传递给组件,但您没有指出它应该分配给哪个属性。

Keep up and good luck.跟上,祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM