【问题标题】:TypeError: Cannot read property 'name' of undefined react errorTypeError:无法读取未定义反应错误的属性“名称”
【发布时间】:2019-12-22 11:06:32
【问题描述】:

每次尝试在输入字段中输入内容时,我都无法在代码中找到解决此错误的方法。 TypeError:无法读取未定义的属性“名称”

我是新手,不太了解。

这是我文件中的所有代码

import React from'react';
import Notelist from '../componenets/notelist';
import { Link } from 'react-router-dom';

export default class NewPage extends React.Component {
    state = {
        note:{
            title: '',
            body: '',
            createdAt: undefined,
            updatedAt: undefined

        }
    }

    updateValue = (e) => {
        const { note } = this.state;

        this.setState({
            note: { ...note, [e.title.name]: e.target.value }
        });
    }

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

        const id = this.props.onSave(this.state.note);

        this.props.history.replace(`/notes/${ id }`);
    }

    render() {
        const { note } = this.state;

        return (
            <div className="note-form">
                <h1>New Note</h1>
                <form onSubmit={this.handleSave}>
                    <div className="note-form-field">
                        <label>Title: </label><br/>
                        <input className="input-txt" type="text" name="title" value={note.title} onChange={this.updateValue}/>
                    </div>
                    <div className="note-form-field note-form-field-text">
                        <br/>
                        <textarea name="body" value={note.body} onChange={this.updateValue} />
                    </div>
                    <div className="note-form-buttons">
                        <button className="btn">Save</button>
                        <Link to="/">Cancel</Link>
                    </div>
                </form>
            </div>
        );
    }
}

这是我得到的完整错误:

TypeError:无法读取未定义的属性“名称” NewPage.updateValue C:/Users/user/react-notes/src/pages/new.js:20

  17 |        const { note } = this.state;
  18 | 
  19 |        this.setState({
> 20 |            note: { ...note, [e.title.name]: e.target.value }
     | ^  21 |        });
  22 |    }
  23 | 

查看编译

【问题讨论】:

  • 嗨,丁,请尝试下面的解决方案,如果有帮助,请告诉我:)

标签: javascript reactjs


【解决方案1】:

event 对象 (e) 没有名为 title 的键,这就是您得到“无法读取未定义的属性名称”的原因。

您需要event.target,它指的是导致此事件发生的元素。

尝试以下操作以动态更新state-value。它将找到一个与元素的name 匹配的键,并为它提供该元素的值(如用户输入):

updateValue = (e) => {
    const { note } = this.state;

    this.setState({
        note: { ...note, [e.target.name]: e.target.value }
    });
}

【讨论】:

  • 非常感谢您的解释和帮助。你的解决方案奏效了!再次感谢!
  • @DinSpataj 不客气!我很高兴这对你有帮助:)
【解决方案2】:

我相信您正在尝试将title 分配为输入字段的键和值作为值。你为什么不试试这个?

updateValue = (e) => {
        const { note } = this.state;

        this.setState({
            note: { ...note, "title": e.target.value }
        });
    }

【讨论】:

    【解决方案3】:

    updateValue 方法中的参数是事件对象,它不会有一个名为title.name 的属性。如果要将标题文本框的值存储到笔记对象的属性标题中 所以你的代码可以是这样的

    this.setState({
          note: { ...note, title: e.target.value }
        });
    

    【讨论】:

      【解决方案4】:

      从 'react' 导入 React,{ Component }

      导出类 Todolist2 扩展组件 {

      state={name:'',items:'',price:'',arr:[],errors:{name:'',items:'',price:''}}
      
      todoSubmit=(event)=>
      {
          event.preventDefault()
        let list=this.state.arr;
        let tododata={name:this.state.name, items:this.state.items, price:this.state.price};
        list.push(tododata);
        this.setState({arr:list});
        console.log(this.state.arr);
      
       
      
      }
      
      
      handle=(event)=>
      {
          const {name,value}=event.target;
          let errors=this.state.error;
          switch(errors)
          {
              case 'name':errors.name=value.length<2?"Name must be 2 character long":'';
      
              case 'items':errors.items=value.length<2?"items must be 2 character long":'';
      
              case 'price':errors.price=value.length<2?"price must be 2 character long":'';
          }
          this.setState({errors,[name]:value})
      
          this.setState({[name]:value})
          console.log(this.state);
      }
      
      
      deldata=(ind)=>
      {
          if (window.confirm('Do u want to delete'))
          {
          let list=this.state.arr;
          list.splice(ind,1);
          this.setState({arr:list});
          }
          // alert('do u want to delete');
      }
      
      render() {
      
          const {errors}=this.state;
          return (
              <div>
                  <h1>ToDo List 2</h1>
                  <form className='container' onSubmit={this.todoSubmit}>
                      <div className="form-group col-md-4">
                          <label>Name:</label>
                          <input type="text" name="name"  className='form-control' onChange={this.handle}/>
                          {errors.name.length>0 && <span className='alert alert-danger'>{errors.name}</span> }
                          
                      </div>
                      <div className="form-group col-md-4" onChange={this.handle}>
                          <label>Items:</label>
                          <input type="text" name="items"  class='form-control'/>
                          {errors.items.length>0 && <span className='alert alert-danger'>{errors.items}</span> }
                      </div>
                      <div className="form-group col-md-4" onChange={this.handle}>
                          <label>Price:</label>
                          <input type="text" name="price"  class='form-control'/>
                          {errors.price.length>0 && <span className='alert alert-danger'>{errors.price}</span> }
                      </div>
                      <input type='Submit' value='Submit' class='btn btn-outline-success'  />
                     
      
                      <table class='table'>
                          <tr>
                              <th>S.no</th>
                              <th>Name</th>
                              <th>Items</th>
                              <th>Price</th>
                              <th>Action</th>
                          </tr>
                          {this.state.arr.map((data,ind)=>
                          
                             <tr>
                                 <td>{ind+1}</td>
                                 <td>{data.name}</td>
                                 <td>{data.items}</td>
                                 <td>{data.price}</td>
                                 <td><button  class="btn btn-info btn-lg " onClick={()=>this.deldata(ind)}>delete </button></td>
                             </tr>
                          )}
                      </table>
      
                  </form>
              </div>
          )
      }
      

      }

      导出默认 Todolist2

      【讨论】:

        猜你喜欢
        • 2019-05-17
        • 1970-01-01
        • 1970-01-01
        • 2020-12-26
        • 2021-11-13
        • 2022-01-14
        • 2022-06-22
        • 2015-10-16
        • 1970-01-01
        相关资源
        最近更新 更多