你好,我是React的新手,试图显示状态下创建的名为Todo的数组,但是,出现错误“ TypeError:无法读取未定义的属性'todos'”。你能告诉我我做错了什么吗?
这是我的代码
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
App.js
import React, { Component } from "react";
import "./App.css";
import Todo from "./components/Todo.js";
import { render } from "@testing-library/react";
function App() {
React.state = {
todos: [
{
id: 1,
title: "Take out the Trash",
completed: false
},
{
id: 2,
title: "Imma out of stock..crystal meth",
completed: false
},
{
id: 3,
title: "google interview...",
completed: false
}
]
};
console.log(React.state.todos);
return (
<div className="App">
<Todo todos={React.state.todos} />
</div>
);
}
export default App;
Todo.js
import React, { Component } from "react";
import { render } from "@testing-library/react";
function Todo() {
return React.props.todos.map((todo) => (
<h3>{todo.title}</h3>
));
}
export default Todo;
这是错误
答案 0 :(得分:2)
使用useState
钩子进行状态管理,并从函数参数中获取props。我以前从未见过这样的事情。以下将起作用:
const todos = React.useState([ ... ])
function Todo(props) {
return props.todos.map((todo) => (
<h3>{todo.title}</h3>
));
}
如果您不熟悉React,请阅读文档https://reactjs.org/docs/getting-started.html
答案 1 :(得分:0)
首先,您可以使用
functional component
和class componet
。
并在React库中不在组件侧props
和state
上使用react(我的意思是React.state
或React.props
是不可能的用例
欢迎与世界互动!根据反应条件,有Component
。
所以您基本上可以像这样制作Component
const SomeComponent = (props) => {
return (<div> {props.title} </div>
}
class SomeComponent extends Component {
state = {
someState: ...
}
render(){
return(
<div> {this.state.somestate} </div>
)
}
}
当使用state
或props
时,可以从this.state
或this.state
(在类组件中)和props
参数(在功能组件中)使用。
App.js
import React, { Component } from "react";
import "./App.css";
import Todo from "./components/Todo.js";
import { render } from "@testing-library/react";
class App extends Component {
state = {
todos: [
{
id: 1,
title: "Take out the Trash",
completed: false
},
{
id: 2,
title: "Imma out of stock..crystal meth",
completed: false
},
{
id: 3,
title: "google interview...",
completed: false
}
]
}
render() {
return (
<div className="App">
<Todo todos={this.state.todos} />
</div>
);
}
}
export default App;
Todo.js
import React, { Component } from "react";
import { render } from "@testing-library/react";
function Todo(props) {
return props.todos.map((todo) => (
<h3>{todo.title}</h3>
));
}
export default Todo;
如果您是程序员的初学者。这个概念有点古玩。因此,我认为这对一些视频讲座很有帮助!晚上好