gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:07:52 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com