【问题标题】:TypeError: Cannot read property 'title' of undefined in ReactTypeError:无法读取 React 中未定义的属性“标题”
【发布时间】:2018-09-26 14:32:01
【问题描述】:

我有一个对象以形式传递给 n=modal 组件

data =[
  {
    _id: "5ba241b4efa8da2f1464ca81", 
    title: "Zero To One", 
    author: "Peter Thiel", 
    isbn: 1279031943, 
    __v: 0
  }
]

我想访问数据上的标题键,但是当我这样做时,我得到了 TypeError。 我尝试使用JSON.stringigy() 将其转换为字符串,但仍然遇到相同的错误。 我正在尝试访问模式中的数据,因此当模式打开时,模式中的输入值是使用表中的数据设置的,因此我可以轻松地编辑它们

当我console.log(data[0]) 时,我得到了对象中的项目,但是当我登录console.log(data[0].title) 时,TypeError 再次出现。

import React, { Component } from 'react';
import './Update.css';
import Search from '../Search/Search';
// import Modal from './Modal/Modal';

const Table = ({ data, openBookDetails }) => (
    <table class="table table-hover">
        <thead>
            <tr class="table-primary">
                <th scope="col">Title</th>
                <th scope="col">Author</th>
                <th scope="col">ISBN</th>
                <th scope="col">No. Of Copies</th>
            </tr>
        </thead>
        <tbody>
            {data.map(row => 
                <TableRow key={row.id} row={row} openBookDetails={openBookDetails}/>
            )}

        </tbody>
    </table>
)

const TableRow = ({ row, openBookDetails }) => (
     <tr class="table-light" onClick={openBookDetails}>
        <th scope="row" >{row.title}</th>
        <td >{row.author}</td>
        <td >{row.isbn}</td>
        <td >24</td>
    </tr>
)

const Modal = ({ closeBookDetails, isBookDetailsOpen, children, data }) => {
    const showHideClassName = isBookDetailsOpen ? 'modal display-block' : 'modal display-none';

    console.log(data[0].title);

    return (
      <div className={showHideClassName}>

                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Update Book</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <div class="form-group">
                                <label htmlFor="title">Title</label>
                                <input type="text" class="form-control" id="title" aria-describedby="title" placeholder="Enter title of book" value={data}/>
                            </div>

                            <div class="form-group">
                                <label htmlFor="author">Author</label>
                                <input type="text" class="form-control" id="author" aria-describedby="author" placeholder="Enter author name" value={data}/>                        
                            </div>

                            <div class="form-group">
                                <label htmlFor="isbn">ISBN</label>
                                <input type="number" min="0" class="form-control" id="isbn" aria-describedby="isbn" placeholder="Enter ISBN number" value={data.title}/>                               
                            </div>
                            <div class="form-group">
                                <label for="copies">Number of Copies</label>
                                <input type="number" min="0" class="form-control" id="copies" aria-describedby="copies" placeholder="Enter the number of copies" value={data.title}/>                  
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary">Save changes</button>
                            <button type="button" class="btn btn-secondary" data-dismiss="modal" onClick={closeBookDetails}>Close</button>
                        </div>

                    </div>
                </div>
          {children}
      </div>
    );
  };

class Update extends Component{
    constructor(props) {
        super(props);

        this.state = {
            value: '',
            suggestions: [],
            setOfAllBooks: [],
            searchedBooks: [],
            isBookDetailsOpen: false,
        };

        this.setTableData = this.setTableData.bind(this);
        this.openBookDetails = this.openBookDetails.bind(this);
        this.closeBookDetails = this.closeBookDetails.bind(this);
    }

    setTableData(searchedBook){
        this.setState({searchedBooks: searchedBook})

        console.log(this.state.searchedBooks)
    }

    openBookDetails(){
        console.log('openBookDetails')
        this.setState({ isBookDetailsOpen: true})
    }

    closeBookDetails(){
        this.setState({ isBookDetailsOpen: false})
    }

    render(){
        return(
            <div>            
                <Search state={this.state} setTableData={this.setTableData} />
                <Table data={this.state.searchedBooks} openBookDetails={this.openBookDetails}/>
                <Modal data={this.state.searchedBooks} isBookDetailsOpen={this.state.isBookDetailsOpen} closeBookDetails={this.closeBookDetails} />
                {/* <Modal /> */}
            </div>
        )
    }
}

export default Update;

【问题讨论】:

  • 你试过这个:console.log(data[0]['title']) 吗?
  • 刚才试过了。没用
  • 这个对象的来源是什么?似乎是一个猫鼬文档,您应该尝试在其上使用 .toObject() 。检查stackoverflow.com/questions/7503450/…
  • 还有一件事,您将未定义的值传递给 TableRow 键,因为该对象不包含 id 属性,仅包含私有 _id。但我相信这不是你错误的根源。
  • toObject() 不起作用。

标签: reactjs


【解决方案1】:

当您将数据作为 this.state.searchedBooks 传递时,您传递的是定义的对象,但从您的代码中,我看不到您实际将值设置为上面列出的数组的位置。您是否缺少部分代码?

如果以 console.log(data[0]) 的形式执行控制台日志,则不会返回错误,但会返回 data[0].title 或此对象的任何其他部分的类型错误。

你能试试这样的吗:

if(data) {
  console.log(data[0].title)
}

所以我们可以判断服务器的响应是否已经到达。那么也许这将有助于进行进一步的评估。

您还考虑过在更新组件中使用箭头函数,这样您就可以消除绑定这些函数的需要。

class Update extends Component{
constructor(props) {
    super(props);

    this.state = {
        value: '',
        suggestions: [],
        setOfAllBooks: [],
        searchedBooks: [],
        isBookDetailsOpen: false,
    };
}

setTableData = (searchedBook) => {
    this.setState({searchedBooks: searchedBook})

    console.log(this.state.searchedBooks)
}

openBookDetails = () => {
    console.log('openBookDetails')
    this.setState({ isBookDetailsOpen: true})
}

closeBookDetails = () => {
    this.setState({ isBookDetailsOpen: false})
}

render(){
    return(
        <div>            
            <Search state={this.state} setTableData={this.setTableData} />
            <Table data={this.state.searchedBooks} openBookDetails={this.openBookDetails}/>
            <Modal data={this.state.searchedBooks} isBookDetailsOpen={this.state.isBookDetailsOpen} closeBookDetails={this.closeBookDetails} />
            {/* <Modal /> */}
        </div>
    )
}

}

更新:

错误是在那个时候还是之后抛出,因为在模态组件中我确实看到了对 data.title 的两个引用会抛出错误。

将这些行更改如下:

<div class="form-group">
                            <label htmlFor="isbn">ISBN</label>
                            <input type="number" min="0" class="form-control" id="isbn" aria-describedby="isbn" placeholder="Enter ISBN number" value={data[0].title}/>                               
                        </div>
                        <div class="form-group">
                            <label for="copies">Number of Copies</label>
                            <input type="number" min="0" class="form-control" id="copies" aria-describedby="copies" placeholder="Enter the number of copies" value={data[0].title}/>                  
                        </div>

在这种情况下,您的输入尝试使用不存在的 data.title 值。不确定这是否行不通。

【讨论】:

  • 数据来自mongoose传递的服务器。然后将此数据放入状态中的 searchedBooks Array 中的 object Array。
  • 数据作为对象成功调用。当我 console.log(typeof(data)) 它是一个对象但为什么我不能遍历该对象是我的问题。\
  • 它仍然会抛出 TypeError。并感谢箭头功能的小提示。大大清理了代码。
【解决方案2】:

我找到了解决办法。

我所做的模态内部

 let selectedBookDetails = []
 data.map(row => selectedBookDetails = row)

然后我像selectedBookDetails.titleselectedBookDetails.authorselectedBookDetails.isbn这样访问数据

现在下一个挑战是编辑它。 感谢大家的贡献。

【讨论】:

    【解决方案3】:

    改用这个:

    console.log(data[0]?.title)
    

    这样就可以了。

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 2021-09-04
      • 2019-12-05
      • 2021-09-04
      • 2020-09-12
      • 2021-02-15
      • 2023-04-01
      相关资源
      最近更新 更多