Reactjs - 数组或迭代器中的每个子项都应该有一个唯一的 "key"属性

标签 reactjs

import React from 'react';
import {Jumbotron} from 'react-bootstrap';
import axios from 'axios';
import './App.css'

export default class Form extends React.Component{

state={
    user:[],
    firstname:'',
    lastname:'',
}
handleChange = event => {
    this.setState({firstname:event.target.value});
    this.setState({lastname:event.target.value});
}

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

    axios.post('http://9795ca45.ngrok.io/api/Docs',{
        fname:this.state.firstname,
        lname:this.state.lastname
    })
    .then( res => {
        console.log(res);
        console.log(res.data);
    })
    .catch((error) =>{
        alert(error);
    })
}

componentDidMount(){
    axios.get('http://9795ca45.ngrok.io/api/Docs')
    .then(res =>{
        const data=res.data;

        const user = data.data;

        this.setState({user});
    })
    .catch((error) =>{
        alert(error);
    })
}

render(){
    return(
        <div>
            <Jumbotron>
                <form onSubmit={this.handleSubmit}>
                <label>
                    firstName:
                    <input type="text" name="firstname" onChange={this.handleChange} />
                    </label>
                <label>
                    LastName:
                    <input type="text" name="lastname" onChange={this.handleChange} />
                    </label>
                    <button type="submit">add</button>
                    </form>
            
                <h1> names </h1>
                <ul> {this.state.user.map(person => <li> {person.lname}</li>)}</ul>
                </Jumbotron>
                </div>
    )
}
}

我对 reatjs 很陌生 我正在尝试将数据发布到 url,但收到请求未找到 500 错误 我使用调试器看到了这一点

警告:数组或迭代器中的每个子项都应该有一个唯一的“key”属性。 检查 Form 的渲染方法.

请帮助我摆脱困境

从url获取数据 但我无法发布数据

请检查它并通过解释更正我的代码

最佳答案

如所写here :

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

您需要向您在 map 内渲染的列表添加一个键。 你的代码应该是这样的:

<ul> {this.state.user.map(person => <li key={person.lname}> {person.lname}</li>)}</ul>

我建议将 key 设置为唯一 ID,而不是姓氏,因为它对于每个人来说都不是唯一的。

关于Reactjs - 数组或迭代器中的每个子项都应该有一个唯一的 "key"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49425552/

相关文章:

reactjs - 无法使用react-native-snap-carousel

css - 使用 CSS 模块时从父项覆盖样式的 'correct' 方法是什么?

node.js - <w> [webpack.cache.PackFileCacheStrategy] 包 : Error: Unable to snapshot resolve dependencies 的缓存失败

javascript - HTML5 视频无法在 Chrome 中加载,但在打开开发者控制台时可以工作

javascript - react : passing state value as parameter to method

javascript - 与 create-react-app 项目 react 的视频标签

reactjs - React-router - Hook useHistory 错误 : Cannot read property 'history' of undefined

reactjs - ReactDOM.Hydrate() 会触发客户端的生命周期方法吗?

reactjs - Eslint-config-rallycoding 安装

javascript - react : Check if key is unique