【问题标题】:How to convert string to JSON object and display in react component?如何将字符串转换为 JSON 对象并在反应组件中显示?
【发布时间】:2021-11-01 23:25:11
【问题描述】:

我对 React 和 Javascript 非常陌生。我正在使用 React 和 Nodejs 创建一个简单的搜索功能,您可以在其中搜索导师。我正在尝试使用 react 打印搜索的输出。我的快递服务器以字符串的形式发送响应。如下所示:

'[{"tutorID":1,"email":"johndoe@sfsu.edu","firstName":"John","lastName":"Doe","courseTeaching":"csc510","imageReference ":" http://localhost:3001/john.png "}]'

我希望能够以表格的形式显示每个键及其值。有人可以帮我实现吗?

我在 react 中的搜索代码如下:

import React, {useState} from 'react';
import "./SearchForm.css"; 
import SearchIcon from '@mui/icons-material/Search';
import DisplayResults from './DisplayResults.js'; 


class SearchForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedCategory: '',
            textSearch: '',
            searchResponse: []
        };

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleInputChange(event) {
        const target = event.target;
        const value = target.value;
        const name = target.name;

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

    handleSubmit(event) {
        event.preventDefault(); 
        let cat = this.state.selectedCategory;
        let searchquery = this.state.textSearch; 

        fetch(`http://localhost:3000/onSubmit?param1=${cat}&param2=${searchquery}`, {
            method: "GET",
            headers: {
                'Content-type': 'application/json'
            }
        })
        .then((result, err) => result.json())
        .then(contents => {
            this.setState({ searchResponse: contents}, function() {
                console.log(this.state.searchResponse);
            })
        });
    }

    render() {
        return (
            <>
            <p className="greeting">Hi, what would you like to search?</p>
            <form onSubmit={this.handleSubmit}>
                
            <div className="wrapper">

               <select class="theme" 
                name="selectedCategory"
                type="category"
                value={this.state.selectedCategory} 
                onChange={this.handleInputChange}>
                    <option value="all">Search All</option>
                    <option value="tutors">Tutors</option>
                    <option value="Courses">Courses</option>
                </select>
    
                <input className="searchBar" 
                name="textSearch" 
                type="text" 
                placeholder="search"
                value={this.state.textSearch}
                onChange={this.handleInputChange}>
                </input> 
                    

                <div className="searchIcon">       
                    <SearchIcon onClick={this.handleSubmit}/>
                </div>
            </div>

            </form>

            <DisplayResults searchResults={this.state.searchResponse}/>
        </>
        )
    }
}

export default SearchForm;

DisplayResults 的代码如下:

import React from 'react'; 

class DisplayResults extends React.Component {

    render() {
        return ( 
                <div>{this.props.searchResults}</div>
        ); 
    }
}

export default DisplayResults; 

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 没有“JSON 对象”这样的东西。 JSON 是 javascript 对象的字符串表示形式。要将 JSON 转换为对象,请使用 theObject = JSON.parse(theString)。要将对象转换为 JSON 字符串,请使用 theString = JSON.stringify(theObject)
  • @DanielBeck 感谢您的回复。我已经更改了代码,以便第二个 .then 接受 contents。我 console.logged contents 它正在返回一个对象。但是,当我尝试将其分配给 SearchForm 文件中的 searchResponse 时,React 不允许我这样做。它给了我一个错误,说“对象作为 React Child 无效”。
  • ...是的,这是因为无法将原始 javascript 对象拖放到 DOM 中。您的 displayResults 组件需要提取您要显示的对象内的任何原语:&lt;div&gt;{searchResults[0].email}&lt;/div&gt; 或等

标签: javascript reactjs


【解决方案1】:

如果响应是 JSON,您可以使用 .map 属性。

在此示例中,我从您的数据集中省略了“ ”(在开头和结尾),以使其成为有效的 json。

let object = [{
"tutorID": 1,
"email": "johndoe@sfsu.edu",
"firstName": "John",
"lastName": "Doe",
"courseTeaching": "csc510",
"imageReference": " http://localhost:3001/john.png "
}]

所以你可能可以做这样的事情来访问这些值。

const listItems = object.map((object) => console.log(object.tutorID))

所以使用 .map 你可以返回一个包含数据的组件,你刚刚映射。

因此,在此之后,您要如何处理数据取决于您。所以你可以创建一个表,或者使用 Bootstrap 中的一个或类似的东西,然后将值映射出来。

<Table>
<p>{object.tutorID}</p>
<p>{object.email}</p>
<p>{object.firstName}</p>
<p>{object.lastName}</p>
...
</Table>

如果我说错了,或者我没有给你想要的答案,请告诉我。

【讨论】:

  • 如何将字符串转换为有效的 JSON 对象?
  • @Leks 你应该使用result.text() 而不是result.json()
  • @ShamPooSham 当我将它从 result.text() 更改为 result.json() 时,我收到以下错误:错误:对象作为 React 子项无效(找到:带有键 {tutorID、电子邮件、名字的对象) ,姓氏,课程教学,图像参考})。如果您打算渲染一组子项,请改用数组。我不太确定为什么会这样。
  • @Leks 确保对象在数组中。Object 对象上没有 .map。但是,如果它是一个对象数组。您可以使用.map。然而,如果你想映射一个对象,你可以使用 object.keys,像这样:stackoverflow.com/questions/14810506/…
  • @Leks 听起来你得到的是一个对象,而不是一个数组。您可以使用现有代码对您的问题进行编辑吗?
【解决方案2】:
  1. [Inside SearchForm] 收到响应后,让我们将您的字符串数据变成可用的东西。使用将您的字符串解析为对象数组 JSON.parse(YOUR_DATA)。然后,您可以将您的 searchResponse 状态设置为此数组。
  2. [Inside DisplayResults] 你有一个对象数组,所以使用YOUR_DATA.map() 遍历它们。你的 map 函数应该返回一些 JSX。在这种情况下,您正在制作一张桌子。 这是一个创建表的函数。 我们使用Object.values(YOUR_OBJECT) 获取所有值(例如John, Doe ...)和Object.keys(YOUR_OBJECT) 获取密钥(例如firstName, lastName)。 您可以在 render() 函数中使用类似的东西来创建表。
    const createTable = () => {
        const tableHeaders = (  // Get the table headers from the first person, OR enter them manually.
            <tr>
                {Object.keys(this.props.searchResults[0]).map(headerTitle => <th>{headerTitle}</th>)}
            </tr>
        );
        // All the content rows of the table.
        const tableRows = this.props.searchResults.map((tutor) => (
            <tr> {/* this is one row of the table. It is filled with td's which each have a piece of information about the tutor. */}
                {Object.values(tutor).map(value => ( // for each of the properties of the tutor, we create a table cell.
                    <td>{value}</td>    
                ))}
            </tr>
        ));
        // The actual table, with table headers and table rows.
        return (
            <table>
                {tableHeaders}
                {tableRows}
            </table>
        );
    }

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 2021-10-06
    • 2019-12-22
    • 1970-01-01
    • 2021-12-20
    • 2011-08-19
    • 2021-05-12
    • 1970-01-01
    • 2017-01-17
    相关资源
    最近更新 更多