Javascript React-this.props在子组件中未定义
我试图在App.js中映射用户并在用户组件中显示它们,但当我通过道具将状态传递给用户组件时,它显示道具未定义 奇怪的是,当我查看react-dev工具时,我发现用户有props.details 这就是js控制台所说的Javascript React-this.props在子组件中未定义,javascript,reactjs,react-props,Javascript,Reactjs,React Props,我试图在App.js中映射用户并在用户组件中显示它们,但当我通过道具将状态传递给用户组件时,它显示道具未定义 奇怪的是,当我查看react-dev工具时,我发现用户有props.details 这就是js控制台所说的 Uncaught TypeError: Cannot destructure property 'firstName' of 'this.props.details' as it is undefined. App.js // import './App.css'; i
Uncaught TypeError: Cannot destructure property 'firstName' of 'this.props.details' as it is undefined.
App.js
// import './App.css';
import React from "react";
import Header from './components/Header';
import User from './components/User';
import AdminSection from './components/AdminSection';
import users from './sampleData';
class App extends React.Component {
state = {
users: {},
}
loadSampleUsers = () => {
this.setState({ users: users });
};
addUser = user => {
const users = { ...this.state.users }
users[`user${Date.now()}`] = user;
this.setState({
users
})
}
componentDidMount() {
this.loadSampleUsers()
}
render() {
return (
<div className="App">
<header className="App-header">
<Header funTime="Alan's Header" />
</header>
<ul>
{Object.keys(this.state.users).map(key => (
<User
key={key}
index={key}
details={this.state.users[key]}
/>
))}
</ul>
<AdminSection users={this.state.users} addUser={this.addUser} />
</div>
)
}
}
export default App;
更新:
当我输入
{this.props.details&&this.props.details.firstName}
时,它就工作了。¯_(ツ)_/“可能详细信息道具未定义,如错误所示。如果详细信息道具具有某些值,是否尝试调试?是否可以添加console.log(this.props)在用户的render方法中,就在解构之前?我认为你的用户对象有一些未定义的键。我建议你在需要存储任意数量的对象时切换到数组,这样更好。数组中有许多有用的方法可以查找、筛选、排序等,而对象没有这些方法,或者使用起来很麻烦。使用对象仅当必须存储的内容数量为静态时,您必须在加载用户之前处理渲染。可能详细信息道具未定义,如错误所示。如果详细信息道具具有某些值,您是否尝试调试?是否可以添加console.log(this.props)在用户的render方法中,就在解构之前?我认为你的用户对象有一些未定义的键。我建议你在需要存储任意数量的对象时切换到数组,这样更好。数组中有许多有用的方法可以查找、筛选、排序等,而对象没有这些方法,或者使用起来很麻烦。使用对象仅当必须存储的内容数量为静态时,您必须在加载用户之前处理渲染。
import React from "react";
class User extends React.Component {
render() {
const { firstName, lastName, email, dashboardAccess } = this.props.details;
return (
<div>
{firstName}, {lastName}, {email}, {dashboardAccess}
</div>
)
}
}
export default User;
const users = {
user1: {
firstName: "Alan",
lastName: "Nubson",
email: "alan@idmedia.ca",
dashboardAccess: true,
},
user2: {
firstName: "Scott",
lastName: "Pasko",
email: "scot@idmedia.ca",
dashboardAccess: true,
},
}
export default users;