【问题标题】:React this is not defined inside a child state iterationReact this 没有在子状态迭代中定义
【发布时间】:2020-04-05 01:12:49
【问题描述】:

我是 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 外面(这个函数效果很好),页面会按我想要的方式显示,但是我需要给每个人添加一个按钮列表,目前我只对人员数据使用静态。 我得到 TypeError: 这是未定义的。我怎样才能做到?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

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

像这样

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

而不是像这样使用function

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

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

带箭头功能:

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

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

【讨论】:

    【解决方案2】:

    你需要 ()=> 和 .bind(this) 使用父函数来引用它们在子组件中的 this

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

    【讨论】:

    • 我正在使用这个 onClick={ () => this.props.addFriend.bind(this) } 但是当我点击时它不起作用。
    【解决方案3】:

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

    从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> 
    ...
    

    【讨论】:

    • 太好了,现在可以渲染了,但是在点击时,我得到了同样的错误
    • 能分享一下父组件吗?
    • 我将其添加到问题中。
    • @Soul7aker 更新了我的答案
    • 我在箭头函数 const handleAddFriend 中得到了一个 Unexpected 标记
    猜你喜欢
    • 2017-06-12
    • 1970-01-01
    • 2022-06-22
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多