gpt4 book ai didi

javascript - 在reactjs中删除重复项后如何从状态值和setstate创建数组

转载 作者:行者123 更新时间:2023-12-04 03:42:23 25 4
gpt4 key购买 nike

React 新手,这是非常基本的表单提交,但我在这里要做的是根据从输入接收到的值创建数组,然后使用数组设置状态,但在设置状态之前也会删除数组中的所有重复项。

import React, { Component } from 'react';

class Chase extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
}
handleSubmit = (e) => {
e.preventDefault();
// Should I create array in the handlesubmit ?
};

handleChange = (e) => {
e.preventDefault()
let newspoo = e.target.value
let createArr= newspoo.split(' ')
let newVal = Array.from(new Set(createArr))
this.setState({ newVal}, () =>{
console.log(newVal)
});
// this works in console but on display I cannot see any values in the UI
};

render() {

const {value} = this.state
return (
<form onSubmit={this.handleSubmit}>
<div>
<label>
Name:
<input
type='text'
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type='submit' value='Submit' />
</div>
<div>
<label>
Output :
{/* I am trying to print the new array here after submitting the form */}
</label>
<p>{value}</p>
</div>
</form>
);
}
}

export default Chase;

最佳答案

问题

您没有使用正确的键更新您的状态,而是添加了一个新的状态变量this.state.newVal

解决方案

handleChange = (e) => {
e.preventDefault()
let newspoo = e.target.value
let createArr= newspoo.split(' ')
let newVal = Array.from(new Set(createArr))
this.setState(
{ value: newVal }, // <-- use correct state key
() => {
console.log(newVal)
},
);
};

关于javascript - 在reactjs中删除重复项后如何从状态值和setstate创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65746284/

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