简体   繁体   中英

index.js:2178 Warning: Each child in an array or iterator should have a unique “key” prop. - reactjs

import React from 'react';
import { Jumbotron, Button } from 'reactstrap';
import axios from 'axios';
import './App.css'


 export default class Form extends React.Component{
constructor(){
super();
this.state={

    fname:'',
    lname:''
};
}
handleChange = event => {
    this.setState({name:event.target.value});;
}

handleSubmit = event =>{
    event.preventDefault();

    const fname = this.state;
    const lname = this.state;

    axios.post('http://37692ae9.ngrok.io/api/addDocs',{fname,lname})
    .then( res => {
        console.log(res);
        console.log(res.data);
    })
    .catch((error) =>{
        alert(error);
    })
}

render(){
    return(
        <div>
        <div className="container">
            <Jumbotron fluid>
                <form onSubmit={this.handleSubmit}>
                <label>
                    firstName:
                    <input type="text" name="fname" onChange={this.handleChange} />
                    </label>
                    <label>
                    lastName:
                    <input type="text" name="lname" onChange={this.handleChange} />
                    </label>
                    <Button type="submit">add</Button>
                    </form>
                    </Jumbotron>
                    </div>

                </div>
    )
}
 }

please help me to post the two data in the url using axios whenever i was trying to send its not going..

the bug is Warning: Each child in an array or iterator should have a unique "key" prop.

i am very new to reactjs so please help me to solve this problem and make my code to execute

When you iterate through an array and render something for each element in React, you need to assign a 'key' property to each element. This helps React's virtual DOM keep track of the changes that take place. Luckily, this is a pretty simple task.

Say you had an array of names: const names = ['tom', 'jerry', 'frank', 'lilly']

to iterate through these and render a paragraph tag for each name without React complaining you would do this in your return method of your component:

return (
 {
   names.map((name, index) => <p key={index}>{name}</p>
 }
)

You create a key for each element you are rendering in the list. It can be anything so long as it is unique. So if you wanted to, you could have the names be the key, but it might no be good practice if you have duplicate values in your array.

its help me

{
    items.map((post, index)  => (
        <PostItem key={index} {...post} />
    ))
}

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