【发布时间】: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}¶m2=${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.loggedcontents它正在返回一个对象。但是,当我尝试将其分配给SearchForm文件中的searchResponse时,React 不允许我这样做。它给了我一个错误,说“对象作为 React Child 无效”。 -
...是的,这是因为无法将原始 javascript 对象拖放到 DOM 中。您的 displayResults 组件需要提取您要显示的对象内的任何原语:
<div>{searchResults[0].email}</div>或等
标签: javascript reactjs