![](/img/trans.png)
[英]Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children, use an array instead
[英]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
我有這兩個文件要連接到節點文件。 搜索.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
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);
}
}
我在 stackoverflow 上發現了一個類似的錯誤,他們用{user.map(user => <div>{user.name}</div>)}
修復了它,但這給了我ReferenceError: user is not defined
。 作為參考,我的節點文件如下:
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) {
}
})
基本上,我只希望用戶有一個按鈕,他們可以在其中輸入名稱,然后在數據庫中搜索該名稱。
您所在的州沒有user
,但您正在嘗試將其與 state 功能一起使用,這就是問題所在。
您正在形成 API,它返回 Object 或數組 collections:
res.json({rank: resp.rows});
而不是this.state.user
,使用this.state.user.rank
並在 React Element 中訪問它的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.