【问题标题】:How to create array from state value and setstate after removing duplicates in reactjs在reactjs中删除重复项后如何从状态值和setstate创建数组
【发布时间】:2021-04-21 02:00:56
【问题描述】:

React 新手,这是非常基本的表单提交,但我在这里要做的是根据从输入接收的值创建数组,然后使用数组创建数组,但在 setState 之前还删除数组中的任何重复项。

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;

【问题讨论】:

    标签: javascript arrays reactjs state setstate


    【解决方案1】:

    问题

    您没有使用正确的密钥 value 更新您的状态,而是添加了一个新的状态变量 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)
        },
      );
    };
    

    【讨论】:

    • 感谢@Drew 它起作用了,你能解释一下handleSubmit 应该保持状态还是只有它才有阻止默认方法?
    • @Zeba 对不起,我不太明白你在问什么。我们在form 元素的onSubmit 事件上使用event.preventDefault(),因此不会执行任何默认表单操作,主要是发生的导航/页面重新加载。你能澄清你对我的要求吗?
    • 我很抱歉让@Drew 感到困惑,我的意思是这个问题,我在这里找到了答案stackoverflow.com/q/28479239/11737583
    • @Zeba 啊,好的,太好了。如果我的回答充分解决了您的问题/问题,那么我邀请您将其标记为已接受的答案。如果您发现它有用/有帮助,请不要忘记也投票(如果您还没有)。干杯。
    猜你喜欢
    • 2021-03-10
    • 1970-01-01
    • 2021-06-17
    • 2020-01-04
    • 2020-12-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    相关资源
    最近更新 更多