如何将对象推送到状态对象数组,如何与Typescript反应

时间:2019-04-29 08:54:31

标签: arrays reactjs typescript

我需要维护存储在状态对象中的对象数组。基本上,每当我单击“添加”按钮时,我都需要将每个对象推送到该数组中。这基本上应该将该对象存储在数组中。

当我尝试提交时,我也无法获取适当的值吗? 我要去哪里错了?

基本上我想要的结构是:

users= [
        {"name":"xxx","email":"yyy","phone":"656"},
        {"name":"yyy","email":"xxx","phone":"55"}
       ];
import * as React from 'react';
interface IState{
    users : Account[];
}
interface Account{
  name: string;
  email: string;
  phone: string
}

export default class App extends React.Component<{},IState> {

    constructor(props:any){
       super(props);
       this.state= { 
                         users: []
                   }
    }


  handleChange = ( event: React.ChangeEvent<HTMLInputElement>) => {
   this.setState({
    users:{
      ...this.state.users,
      [event.target.name]:event.target.value
    }
    })
  }

  onAdd = () => {
     this.setState((prevState) => ({
     users: [...prevState.users],
    }));
    console.log(this.state.users); // Unable to get the proper info
  }

  render(){
   <React.Fragment>
     <form onSubmit={this.onAdd}>
       <input type="text" onChange={(e:any) => this.handleChange(e)} name={"name"} />
       <input type="text" onChange={(e:any) => this.handleChange(e)} name={"email"} />
       <input type="text" onChange={(e:any) => this.handleChange(e)} name={"phone"} />
       <button type="submit">Add</button>
      </form>
   </React.Fragment>
  }
}

3 个答案:

答案 0 :(得分:2)

像下面一样更新onAdd,因为setState方法异步更新状态,因此调用后无法立即获得状态,但是可以在{{ 1}}方法,该方法在状态更新后被调用

setState

答案 1 :(得分:1)

要纠正的事情:-

1)您仅对一个用户以及所有用户使用一个状态变量users。因此,创建两个状态变量,一个用于临时存储用户数据,另一个users变量用于存储所有用户数据。

2)您正在尝试在setState之后访问console.log(this.state.users);,但是它不在回调中,setState是异步的,它应该在setState的回调中。

3)用户提交表单时,页面将刷新,这是应用程序的默认行为,我们需要e.preventDefault();才能覆盖此行为。

4)对单个输入文本框使用状态,以便您可以对字段应用验证等。

import * as React from "react";
import { render } from "react-dom";

interface IState {
  users : Account[],
  user: Account
}

interface Account{
  name: string;
  email: string;
  phone: string
}

class App extends React.Component<{}, IState> {
  constructor(props: any) {
    super(props);
    this.state = {
      users: [],
      user: {name: '', email:'', phone: ''}
    }
  }

  handleChange = (event: React.FormEvent<HTMLInputElement>) => {
    this.setState({
      user: {
        ...this.state.user,
        [event.currentTarget.name]: event.currentTarget.value
      }
    });
  };

  onAdd = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    this.setState(
      { 
        users: [...this.state.users, this.state.user],
        user: {name:'', email: '', phone: ''}
      },
      () => {
        console.log("updated state", this.state.users);
      }
    );
  };

  public render() {
    const { name, email, phone } = this.state.user;
    return (
      <form onSubmit={this.onAdd}>
        <input type="text" onChange={this.handleChange} value={name} name="name" />
        <input type="text" onChange={this.handleChange} value={email} name="email" />
        <input type="text" onChange={this.handleChange} value={phone} name="phone" />
        <button type="submit">Add</button>
      </form>
    );
  }
}

render(<App />, document.getElementById("root"));

改进区域-您可以声明字段数组,例如fields = ['name','phone','email'],并在render函数中进行映射,这样一来,您需要一次编写任何表单的字段可以添加。

希望有帮助!

答案 2 :(得分:-1)

const PROGMEM uint_16_t patterns[] = {
// BA9876543210  Led Pins
 0b000101101100, //foo: 2, 5, 6, 8, 3
 0b000010000010, //bar: 1, 7
 0b111111001000, //baz: 6, 10, 9, 11, 7, 8, 3
// ... 
};

您正在将export default class App extends React.Component<{},IState> { state = { users: [], text: '', } handleChange = ( event: React.ChangeEvent<HTMLInputElement>) => { this.setState({ [e.target.name]: e.target.value }) } onAdd = () => this.setState({ users:[ ...this.state.users, { e.target.name: e.target.value, e.target.email: e.target.value, e.target.phone: e.target.value } ] }) render(){ <React.Fragment> <form onSubmit={this.onAdd}> <input type="text" onChange={(e:any) => this.handleChange(e)} name={"name"} /> <input type="text" onChange={(e:any) => this.handleChange(e)} name={"email"} /> <input type="text" onChange={(e:any) => this.handleChange(e)} name={"phone"} /> <button type="submit">Add</button> </form> </React.Fragment> } } 设置为数组,然后使用users将其转换为对象。尝试看看是否可行