React这不是在子状态迭代中定义的



我是React的新手,我正在尝试更改子级的父级状态,我有一个人员列表,我已经使用Object.keys进行了迭代,我需要在每次迭代中都出现一个按钮,并处理父级的"添加好友"功能。

import React, { Component } from 'react';
class People extends Component {
constructor(props) {
super(props);
}
render() {
let friends = this.props.userData;
return (
<div>
<div className="title">
<h1>People You might know</h1>
</div>
<div>
<div>
{Object.keys(friends).map(function (key) {
var friend = friends[key];
return (<div className="userData">
<img src={friend.profilePic} className="profile-photo" alt="userPhoto" />
<div className="data" id="name">
{friend.name}
<br />
<div className="city">
Ciudad: {friend.city}
</div>
</div>
{/* this is the one that isnt working */}
<button onClick={this.props.addFriend}>Add as a friend</button>   
</div>);
})}
</div>
</div>
</div>);
}
}
export default People;

这是的父组件

import React, { Component } from 'react';
import Profile from './profile';
import People from './people';
import Photo from './meSmall.jpg';
import FriendList from './friendList';
import './App.css';
import './profile.css';
import './people.css';
class App extends Component{
constructor(props){
super(props);
this.state = {
userData: {
name: "User1",
city: "city2",
profilePic: Photo    
},
friendList:{
},
peopleList:{
f1:{
name: "Maria",
city: "city3",
profilePic: "./images/f1.jpg",  
},
f2:{
name: "James",
city: "city4",
profilePic: "./images/f2.jpg"       
}  
}            
}
this.handleAddFriend = this.handleAddFriend.bind(this);
}
render(){
return (
<div className="App">
<div className="profile">
<Profile userData={this.state.userData}/>
</div>  
<div>
<FriendList friendList = {this.state.friendList}/>
</div>      
<div className="people">
<People userData = {this.state.peopleList} addFriend={this.handleAddFriend}/>
</div>         
</div>
);    
}
handleAddFriend(){
this.setState({
friendList:{
f1:{
name: "Maria Almagro",
city: "Cordoba",
profilePic: "./images/f1.jpg",  
},
f2:{
name: "Pablo Gramajo",
city: "Cafayate",
profilePic: "./images/f2.jpg"       
}
}
})
}
}
export default App;

如果我不把onClick和函数放在Object.keys之外,或者把按钮放在Object/keys之外(函数工作得很好(,页面会按照我的意愿显示,但我需要为列表中的每个人添加一个按钮,目前我只对人的数据使用静态状态。我得到TypeError:这是未定义的。我该怎么做?

解决onClick问题的一个简单方法是使用arrow functionmap方法中

像这样

{Object.keys(friends).map((key) => { ... 

而不是像这个那样使用function

{Object.keys(friends).map(function(key) { ... 

我已经复制了你的代码,并在我的本地上进行了测试。它有效。

带箭头功能:

  • 它们不创建自己的this,因此使用了封闭的this

  • this只是指在箭头函数定义的环境中(即箭头函数的"外部"(的this的值,并且在函数的整个生命周期中保持不变,并且始终与最近的非箭头父函数中的this的值绑定

您需要((=>和.bind(this(使用引用其this内部子组件的父函数

onClick={() => this.props.addFriend.bind(this)}

您要么需要绑定您拥有的每个处理程序,要么使用箭头函数。我更喜欢箭头功能。因此,您需要更新以下内容;

从handleAddFriend开始,将所有函数转换为箭头函数;


const handleAddFriend = (friend) => {
// TODO: set the input friend here
console.log('hey you triggered handleAddFriend with; ', friend);
this.setState({
...
...
};

现在您可以在子组件中使用它,如下所示;

...
<button onClick={() => this.props.addFriend(friend);}>Add as a friend</button> 
...

最新更新