【问题标题】:react js adding object to state array反应js将对象添加到状态数组
【发布时间】:2019-06-16 13:25:42
【问题描述】:

在 React js 中测试一些东西,我的一些逻辑有一些问题。我试图从表单中的输入中获取值,然后在提交该表单时,我想获取输入值的对象并将它们添加到我的 ctcList 数组中。我正在尝试使用 spread 的 es6 功能将我当前的 newCtc 状态与我的 ctcList 状态连接起来。当我控制台日志时,我得到 newCtc 值,但 ctcList 数组为空。任何帮助表示赞赏。

谢谢!

import React, { Component } from 'react';
import Contact from './Contact';
import TestData from './TestData';


class ContactList extends Component {
  constructor(props){
    super(props);
    this.state = {
      name: '',
      test1:'',
      test2:'',
      newCtc:{},
      ctcList:[],
      arr: []
    }
  }

  async componentDidMount() {
    try{
      const result = await fetch('https://jsonplaceholder.typicode.com/users')
      const data = await result.json()
      this.setState({arr:data})

    }catch(err){
      console.log(err)
    }
  }


  onChangeInput = (e)=>{
    const target = e.target;
    const name = target.name;
    const value = target.value;
    console.log(value)
    this.setState({
      [name]: value
    });
  }

  newSubmit = (e) =>{
    e.preventDefault();



    this.setState(Object.assign(this.state.newCtc,{test1:this.state.test1, test2:this.state.test2}));


    console.log(this.state.newCtc)

    this.addContact();



    this.clearInput();
    console.log(this.state.newCtc);

    }



    addContact = ()=>{
      this.setState({ ctcList:[ ...this.state.ctcList, this.state.newCtc] });
      console.log(this.state.ctcList);
    };




    clearInput = ()=>{
      this.setState({test1:'',test2:''});
      this.setState(Object.assign(this.state.newCtc,{test1:'', test2:''}));
    };

  render() {


    return (
      <div>
      <Contact firstName = {this.state.name} lastName='mcdaniel' phoneNumber = '585-721-3824' />
      <input type = 'text' name = 'name' onChange = {this.onChangeInput}></input>

      <TestData data={this.state.arr} />  


      <form onSubmit = {this.newSubmit}>

      <input type='text' name={'test1'} value={this.state.test1} onChange = {this.onChangeInput}

        />
      <input type='text' name={'test2'} value={this.state.test2}  onChange = {this.onChangeInput}

        />
      <button type='submit'> submit </button>
      </form>

    </div> 
    )
  }
}
export default ContactList;

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

试试这个,注意setState的回调函数

import React, { Component } from 'react';



class ContactList extends Component {
  constructor(props){
    super(props);
    this.state = {
      name: '',
      test1:'',
      test2:'',
      newCtc:{},
      ctcList:[],
      arr: []
    }
  }

  async componentDidMount() {
    try{
      const result = await fetch('https://jsonplaceholder.typicode.com/users')
      const data = await result.json()
      this.setState({arr:data})

    }catch(err){
      console.log(err)
    }
  }


  onChangeInput = (e)=>{
    const target = e.target;
    const name = target.name;
    const value = target.value;

    this.setState({
      [name]: value
    });
  }

  newSubmit = (e) =>{
    e.preventDefault();

    this.setState(Object.assign(this.state.newCtc,{test1:this.state.test1, test2:this.state.test2}), ()=>{
        console.log('newctc', this.state.newCtc)
        this.addContact();            
    });

    }



    addContact = ()=>{
        let newCtcList = [...this.state.ctcList];
        newCtcList.push({...this.state.newCtc});
        console.log('newctc addcontact', this.state.newCtc);
        console.log('newctclist',newCtcList);

      this.setState({ ctcList: newCtcList }, ()=>{
        console.log(this.state.ctcList);
        this.clearInput();
      });

    };




    clearInput = ()=>{
      this.setState({test1:'',test2:''});
      this.setState(Object.assign(this.state.newCtc,{test1:'', test2:''}));
    };

  render() {


    return (
      <div>

      <input type = 'text' name = 'name' onChange = {this.onChangeInput}></input>



      <form onSubmit = {this.newSubmit}>

      <input type='text' name={'test1'} value={this.state.test1} onChange = {this.onChangeInput}

        />
      <input type='text' name={'test2'} value={this.state.test2}  onChange = {this.onChangeInput}

        />
      <button type='submit'> submit </button>
      </form>

    </div> 
    )
  }
}
export default ContactList;

【讨论】:

    【解决方案2】:

    这里有问题

    // newCtc is empty => so Object.assign, simply returns {test1: 'some value', test2: //  somevalue }
    // this.setState then merges this into the array, so newCtc is not actually updated
    // but the properties test1 and test2
    this.setState(Object.assign(this.state.newCtc,{test1:this.state.test1, test2:this.state.test2}));
    
    import React, { Component } from 'react';
    import Contact from './Contact';
    import TestData from './TestData';
    
    
    class ContactList extends Component {
      constructor(props){
        super(props);
        this.state = {
          name: '',
          test1:'',
          test2:'',
          newCtc:{},
          ctcList:[],
          arr: []
        }
      }
    
      async componentDidMount() {
        try{
          const result = await fetch('https://jsonplaceholder.typicode.com/users')
          const data = await result.json()
          this.setState({arr:data})
    
        }catch(err){
          console.log(err)
        }
      }
    
    
      onChangeInput = (e)=>{
        const target = e.target;
        const name = target.name;
        const value = target.value;
        console.log(value)
        this.setState({
          [name]: value
        });
      }
    
      newSubmit = (e) =>{
        e.preventDefault();
    
        const ctcCopy = Object.assign({}, this.state.newCtc);
    
        this.setState({newCtc: Object.assign(ctcCopy, {
          test1: this.state.test1,
          test2: this.state.test2,
        })})
    
    
        console.log(this.state.newCtc)
    
        this.addContact();
    
    
    
        this.clearInput();
        console.log(this.state.newCtc);
    
        }
    
    
        // I would also copy this.state.newCtc
        addContact = ()=>{
          this.setState({ ctcList:[ ...this.state.ctcList, ...this.state.newCtc] });
          console.log(this.state.ctcList);
        };
    
    
    
    
        clearInput = ()=>{
          this.setState({test1:'',test2:''});
          const ctcCopy = Object.assign({}, this.state.newCtc);
    
          this.setState({newCtc: Object.assign(ctcCopy, {
            test1: this.state.test1,
            test2: this.state.test2,
          })})
        };
    
      render() {
    
    
        return (
          <div>
          <Contact firstName = {this.state.name} lastName='mcdaniel' phoneNumber = '585-721-3824' />
          <input type = 'text' name = 'name' onChange = {this.onChangeInput}></input>
    
          <TestData data={this.state.arr} />  
    
    
          <form onSubmit = {this.newSubmit}>
    
          <input type='text' name={'test1'} value={this.state.test1} onChange = {this.onChangeInput}
    
            />
          <input type='text' name={'test2'} value={this.state.test2}  onChange = {this.onChangeInput}
    
            />
          <button type='submit'> submit </button>
          </form>
    
        </div> 
        )
      }
    }
    export default ContactList;
    
    
    

    【讨论】:

      猜你喜欢
      • 2017-06-05
      • 1970-01-01
      • 2021-10-01
      • 2017-08-17
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      相关资源
      最近更新 更多