[英]Error: Objects are not valid as a React child (found: object with keys {rank}). If you meant to render a collection of children, use an array instead
I have these two files that I want to connect to a node file.我有这两个文件要连接到节点文件。 search.js
搜索.js
import React from "react";
import { getInfo } from "../lib/utilSearch.js";
export default class Search extends React.Component {
constructor(props) {
super(props);
this.state = {search:""};
}
handleUpdate(evt) {
this.setState({search: evt.target.value});
}
async handleSearch(evt) {
const user = await getInfo(this.state.search);
// console.log(user);
this.setState({user});
}
render() {
return (
<div>
<h3 className="text">Enter a name below to search for it and see your rank!</h3>
<p><input type='text' value={this.state.search} onChange={this.handleUpdate.bind(this)} /></p>
<button className='button-style' onClick={this.handleSearch.bind(this)}>Search</button>
{this.state.user ? <div>
<p>{this.state.user} </p>
</div> : null}
</div>
)
}
}
utilSearch.js utilSearch.js
require("isomorphic-fetch");
function getCuber(time) {
return fetch('http://localhost:3001/rank?q=${time}').then(function(resp) {
return resp.json();
});
}
function handleError(error) {
return null;
}
module.exports = {
getInfo: function(time) {
return getCuber(time).catch(handleError);
}
}
I found a similair error on stackoverflow where they fixed it with {user.map(user => <div>{user.name}</div>)}
, but that gives me ReferenceError: user is not defined
.我在 stackoverflow 上发现了一个类似的错误,他们用
{user.map(user => <div>{user.name}</div>)}
修复了它,但这给了我ReferenceError: user is not defined
。 For reference, my node file is as follows:作为参考,我的节点文件如下:
app.get("/rank", async (req,res) => {
try {
const name = req.query.name;
const temp = 'SELECT name,time,rank FROM (SELECT name,time, RANK() OVER (ORDER BY time ASC) rank FROM times) t WHERE name=$1';
const resp = await pool.query(temp,[name]);
res.json({rank: resp.rows});
} catch (err) {
}
})
Basically, I just want the user to have a button where they can enter a name and then search for that name in the database.基本上,我只希望用户有一个按钮,他们可以在其中输入名称,然后在数据库中搜索该名称。
You do not have user
in your states but you are trying to use it with state features, that's the problem.您所在的州没有
user
,但您正在尝试将其与 state 功能一起使用,这就是问题所在。
You are forming API which returns Object or Array collections:您正在形成 API,它返回 Object 或数组 collections:
res.json({rank: resp.rows});
Instead of this.state.user
, use this.state.user.rank
and access it's data in React Element.而不是
this.state.user
,使用this.state.user.rank
并在 React Element 中访问它的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.