简体   繁体   中英

Having trouble passing react props value to another component

i am having trouble passing a prop to another component This code is from my App Component it is triggered by onClick

 addServer() {
    let serverArr = ['Server 1','Server 2'];
    serverArr.push(this.state.serverName);
    return (
        <ServerList server={serverArr}/> // Here i am passing the array as prop
      )

  }

here is a code from the component i want to use the prop, i am trying to display the passed in props

export class ServerList extends React.Component {
    render(){
        let server = this.props.server.map((item, index) => {
           return <li key={index}> {item} </li>;
        })
        return (
                <div className="container-server">
                <ul> {server} </ul>
                </div>
        )
   }
}

I'm not sure about your case but my guess is , since you are mutating the array by using

array.push()  

you should call

 this.forceUpdate() 

function for re-render the component so just try this

addServer() {
let serverArr = ['Server 1','Server 2'];
serverArr.push(this.state.serverName);
this.forceUpdate();
return (
    <ServerList server={serverArr}/> // Here i am passing the array as prop
  )  }

What is the value of this.state.serverName on the serverArr.push line? Console.log this.state.serverName before that line.

Also console.log serverArr after serverArr.push line.

Then console.log server after let server line.

You should also console.log this.props.server before let sever line.

Making these checks you should pinpoint where the error is.

Finally, what is the actual error. Is something written in the console, or you don't see the component, or component is rendered strangely?

EDIT: You should have serverArr in state in AppComponent , and then render it. For example:

class AppComponent extends React.Component {

    constructor(props){
         super(props);
         this.state = {serverArr: ['Server 1', 'Server2']};
         this.addServer = this.addServer.bind(this);
    }

    function addServer() {
    }

    render(){
        return (
              <div>
                <ServerList server={serverArr}/>
                <button onClick={this.addServer}>Add</button>
              </div>
        );
    }
}

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