我一直在关注YouTube上有关React的教程,但由于它已经过时,所以我遇到了错误。
我用Google搜索,发现有些人可以通过添加构造函数来解决它,并且我试图将构造函数添加到代码中(这在本教程中没有完成),但仍然会出现相同的错误。
这是App类
import React, { Component } from 'react';
import Main from './components/Main';
import './App.css';
class App extends Component {
state = {
types: [
{
id: 1,
title: "Bug",
chosen: false
},
{
id: 2,
title: "Task",
chosen: false
},
{
id: 3,
title: "Issue",
chosen: false
},
],
states: [
{
id: 1,
title: "New",
chosen: false
},
{
id: 2,
title: "In progress",
chosen: false
},
{
id: 3,
title: "Done",
chosen: false
},
]
}
render() {
return (
<div className="App">
<Main main={this.state.main} />
</div>
);
}
}
export default App;
这是Main.js
import React, { Component } from 'react';
class Main extends Component {
constructor(props) {
super(props);
}
render() {
return this.props.main.map((mai) => (
<h3>{mai.title}</h3>
));
}
}
export default Main;
我收到错误消息“ TypeError:this.props.main未定义”
答案 0 :(得分:1)
您传递{strong>未定义的js
组件<Main />
。您可能打算通过this.state.main
或this.state.states
?
答案 1 :(得分:1)
查看错误:"TypeError: this.props.main is undefined"
。
这意味着您在props对象内没有'main'属性。
但是您确实将其传递到了jsx的“ main”属性中,但问题是要传递的内容:
<Main main={this.state.main} />
=>您试图传递状态对象的'main'属性,但该属性不存在。您只有“类型”和“状态”属性。
因此,您有2个选择:
将其中之一重命名为“ main”,并按原样保留代码。
传递其他状态属性之一,例如<Main main={this.state.states} />
。
答案 2 :(得分:0)
已将您的代码更新为可工作的代码,请查看并提供反馈,
建议仅在需要无状态组件以提高性能时才使用类组件。
Main = (props) => {
console.log(props);
return (props && props.map((mai, index) => (
<><h3 key={index}>{mai.title}</h3></>)
));
}
render() {
return (
<div className="App">
{this.Main(this.state.states)}
</div>
);
}
下面的更新代码,
import React from "react";
import ReactDOM from "react-dom";
import { Component } from 'react';
class App extends Component {
state = {
types: [
{
id: 1,
title: "Bug",
chosen: false
},
{
id: 2,
title: "Task",
chosen: false
},
{
id: 3,
title: "Issue",
chosen: false
},
],
states: [
{
id: 1,
title: "New",
chosen: false
},
{
id: 2,
title: "In progress",
chosen: false
},
{
id: 3,
title: "Done",
chosen: false
},
]
}
Main = (props) => {
console.log(props);
return (props && props.map((mai, index) => (
<><h3 key={index}>{mai.title}</h3></>)
));
}
render() {
return (
<div className="App">
{this.Main(this.state.states)}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);