简体   繁体   中英

Reactjs: How to make Users age displays on the users button instead of displaying on the page using reactjs

I have five Users in the array.

The code below displays each users info from the arrays when pop up button is clicked and everything works fine.

Now I have created a form to update each user's age based on their respective person Id on form submission via call to nodejs backend. Am actually getting the result from nodejs backend..

Here is my issue.

Each time I entered age in the input and click on submission button Eg. for user 1 . Instead of the age result to appear near that very user 's name in the space provided in the button, it will appears on the body of the page as can be seen from screenshots provided. 截图

If call it as props For instance {this.props.messages.personAge}

as per below

   <button
            onClick={() => this.open(this.props.data.id, this.props.data.name)}
          >
(Age should Appear Here-- ({this.props.messages.personAge})--)
            {this.props.data.name}
          </button>

It shows error

TypeError: Cannot read property 'personAge' of undefined at User.render

Here is how am getting the response from nodejs server

componentDidMount(){

this.socket = io('http://localhost:8080');
this.socket.on('response message', function(data){
            addAge(data);
        });

        const addAge = data => {
            console.log(data);
            //this.setState({messages: [...this.state.messages, data]});
         this.setState({messages: [data]});
        };
} 

below is how am displaying the age result for each unique user

{this.state.messages.map((message, i) => {

//if (message.personId == this.props.data.id) {
//if (message.personId == person.id) {

if (message.personId) {

          return (
            <div key={i}>
       <div>       
 ({message.personAge}--years)
            </div>
              </div>
          )


  } 
        })}

</ul>

Here is the Entire Code

import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import { Link } from 'react-router-dom';
import axios from 'axios';
import io from "socket.io-client";


class User extends React.Component {
  open = () => this.props.open(this.props.data.id, this.props.data.name);
  render() {
    return (
      <React.Fragment>
        <div key={this.props.data.id}>

          <button
            onClick={() => this.open(this.props.data.id, this.props.data.name)}
          >
(Age should Appear Here-- ({this.props.messages})--)
            {this.props.data.name}
          </button>
        </div>
      </React.Fragment>
    );
  }
}

class OpenedUser extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hidden: false,
 personId: '',
 personAge: '',
    };

  }



componentDidMount(){

this.socket = io('http://localhost:8080');

var userId= this.props.data.id;

} 


sendPost = (personId,personAge) => {
alert(personId);
alert(personAge);

this.socket.emit('messageUpdate', {
                personId: personId,
                personAge: personAge,

            });


         this.setState({personId: ''});
         this.setState({personAge: ''});

        }

  toggleHidden = () =>
    this.setState(prevState => ({ hidden: !prevState.hidden }));

  close = () => this.props.close(this.props.data.id);

  render() {





    return (



      <div key={this.props.data.id} style={{ display: "inline-block" }}>




        <div className="wrap_head">
          <button onClick={this.close}>close</button>
          <div>user {this.props.data.id}</div>
          <div>name {this.props.data.name}</div>

 {this.state.hidden ? null : (
            <div className="wrap">
              <div className="wrap_body">Update Age Info</div>


<div> </div>

 <div>






                                 <label></label>
<input type="text"  placeholder="personAge" value={this.state.personAge} onChange={ev => this.setState({personAge: ev.target.value})}/>
                                <br/>

                                <span onClick={ () => this.sendPost(this.props.data.id, this.state.personAge)} className="btn btn-primary">Update Age</span>
                            </div>


            </div>
          )}
        </div>
      </div>

    );
  }
}
class App extends React.Component {
  constructor() {
    super();

    this.state = {

  showingAlert_UserTyping: false,
      shown: true,
      activeIds: [],
 messages: [],
      data: [
        { id: 1, name: "user 1" },
        { id: 2, name: "user 2" },
        { id: 3, name: "user 3" },
        { id: 4, name: "user 4" },
        { id: 5, name: "user 5" }
      ]
    };
  }





componentDidMount(){

this.socket = io('http://localhost:8080');

this.socket.on('response message', function(data){
            addAge(data);

            console.log(' am add message' +data);
        });


        const addAge = data => {
            console.log(data);
            //this.setState({messages: [...this.state.messages, data]});
         this.setState({messages: [data]});
        };




} // close component didmount


  toggle() {
    this.setState({
      shown: !this.state.shown
    });
  }


  open = (id,name) => {
    this.setState(prevState => ({
      activeIds: prevState.activeIds.find(user => user === id)
        ? prevState.activeIds
        : [...prevState.activeIds, id]
    }));
  };

  close = id => {
    this.setState(prevState => ({
      activeIds: prevState.activeIds.filter(user => user !== id)
    }));
  };

  renderUser = id => {
    const user = this.state.data.find(user => user.id === id);
    if (!user) {
      return null;
    }
    return (
      <OpenedUser  messages={this.state.messages}
        key={user.id}
        data={user}
        close={this.close}
      />
    );
  };

  renderActiveUser = () => {
    return (
      <div style={{ position: "fixed", bottom: 0, right: 0 }}>
        {this.state.activeIds.map(id => this.renderUser(id))}
      </div>
    );
  };


  render() {

    return (
      <div>


<ul>
{this.state.messages.map((message, i) => {

//if (message.personId == this.props.data.id) {
//if (message.personId == person.id) {

if (message.personId) {

          return (
            <div key={i}>
       <div>       
 ({message.personAge}--years)
            </div>
              </div>
          )


  } 
        })}

</ul>


{this.state.data.map(person => {


return (
  <User key={person.id} data={person}  open={this.open} />
);

        })}
        {this.state.activeIds.length !== 0 && this.renderActiveUser()}
      </div>
    );
  }
}

Here is how I solved the issue:

I created a const resultdata and using map() and Filter() function.

Here is how I initialized the the variable resultdata and then pass it within state.data.map() method

const resultdata = this.state.messages.filter(res => res.personId == person.id).map(res => res.personAge));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM