gpt4 book ai didi

javascript - React 中的状态仍然未定义

转载 作者:行者123 更新时间:2023-11-30 11:10:54 25 4
gpt4 key购买 nike

我是网络开发新手,正在尝试学习 React。我一直被困在我一直关注的教程中,似乎无法通过它。我正在尝试将一些数据存储在 state 中。但是,当我尝试引用它时,出现错误“第 45 行:‘characters’未定义 no-undef”。我尝试了几个修复程序,但似乎都没有用。这是我的代码:

import React, {Component} from 'react';
import Table from './Table';
import WhatDoNow from './WhatDoNow';

class App extends Component {
constructor(props) {
super(props);
this.state = {
characters: [
{
'name': 'Charlie',
'job': 'Janitor',
'specialskill': 'Rat Bash'
},
{
'name': 'Mac',
'job': 'Body Guard',
'specialskill': 'Occular Pat-Down'
},
{
'name': 'Dee',
'job': 'Aspring actress',
'specialskill': 'Essence of Bird'
},
{
'name': 'Dennis',
'job': 'Bartender',
'specialskill': 'The Implication'
},
{
'name': 'Frank (But Not Really)',
'job': 'Duper',
'specialskill': 'Egg of Trying Times'
}
]
};
}

render() {
return (
<div className="container">
<h1>The Gang</h1>
<body>
<Table
characterData={characters}
removeCharacter={this.removeCharacter}
/><
/body>
<body><WhatDoNow /></body>
</div>
);
}

removeCharacter = index => {
const {characters } = this.state;

this.setState({
characters: characters.filter( (character, i) => {
return i !== index;
})
});
}
}



export default App;

这是表类。

import React, {Component} from 'react';

class Table extends Component {
render() {
const { characterData } = this.props;

return (
<table>
<TableHeader />
<TableBody characterData={characterData} />
</table>
);
}
}

const TableHeader = () => {
return (
<thead>
<tr>
<th>Name</th>
<th>Job</th>
<th>Special Skills</th>
</tr>
</thead>
);
}

const TableBody = (props) => {

const rows = props.characterData.map((row, index) => {
return (
<tr key={index}>
<td>{row.name}</td>
<td>{row.job}</td>
<td>{row.specialskill}</td>
</tr>
);
});

return (
<tbody>
{rows}
</tbody>
);
}

export default Table;

最佳答案

我认为您使用了未声明的变量 characters 作为错误提示这里:

<Table 
characterData={characters}
removeCharacter={this.removeCharacter}
/>

应该是

<Table 
characterData={this.state.characters}
removeCharacter={this.removeCharacter}
/>

关于javascript - React 中的状态仍然未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com