reactjs - 如何让查询结果显示到屏幕上
问题描述
我开发了一个搜索引擎,可以将输入的结果查询到控制台。但是我希望结果显示在屏幕上。不要太担心变量的名称,我现在正在更新它们。我试图遍历我的状态,但每次单击输入时都会导致错误。表单显示完美,但是当我单击输入时页面崩溃。
import styled from 'styled-components'
import Axios from "axios";
const FirstLabel = styled.label`
display:block;
margin-bottom:3rem;
`
const SecondLabel = styled.label`
display:block;
margin-left:1rem;
margin-bottom:3rem;
`
const ThridLabel = styled.label`
display:block;
margin-left:-2rem;
margin-bottom:3rem;
`
const FirstInput = styled.input`
padding:0.5rem;
display:block;
margin-left:28rem
margin-top:1rem;
padding-left:10rem;
padding-right:10rem;
`
const SecInput = styled.input`
padding:0.5rem;
display:block;
margin-left:27rem
margin-top:1rem;
padding-left:10rem;
padding-right:10rem;
`
const ThrInput = styled.input`
padding:0.5rem;
display:block;
margin-left:30rem
margin-top:1rem;
padding-left:10rem;
padding-right:10rem;
`
const FirstP = styled.p`
margin-left:-1rem;
`
const SecondP = styled.p`
margin-left:-1rem;
`
const ThridP = styled.p`
margin-left:1.3rem;
`
const Input = props => {
console.log("props",props);
const [user,setUser] = useState([])
const handleChanges = event => {
setUser({...user, [event.target.name]: event.target.value});
};
const handleSubmit = event => {
event.preventDefault();
console.log(user);
Axios.get(`https://rickandmortyapi.com/api/character/?name=${user.name}&status=alive`)
.then(res => setUser(res.data.results))
};
return(
<div>
<form onSubmit={handleSubmit}>
<FirstLabel>
<FirstP>Name:</FirstP>
<FirstInput
id="title"
name="name"
type="text"
onChange = { handleChanges}
value={user.name} ></FirstInput>
</FirstLabel>
<SecondLabel>
<SecondP>Role:</SecondP>
<SecInput
type="text"
name="role"
id="role"
onChange = {handleChanges}
value={user.role}></SecInput>
</SecondLabel>
<ThridLabel>
<ThridP>Experience:</ThridP>
<ThrInput
id="Experience"
name="Experience"
type="text"
onChange = {handleChanges}
value={user.Experience} ></ThrInput>
</ThridLabel>
<button>Submit!</button>
</form>
{user.map(i => <div key={i.id}>{i.name}</div>)}
</div>
)
}
export default Input
解决方案
你得到什么错误?您可能希望useState
为您的表单和结果使用不同的。
您正在更改用户状态的数据类型。它被初始化为一个数组,但设置为 中的一个对象handleChanges
,我假设返回到 中的一个数组handleSubmit
。不知道这是否是一个原因,但这不是一个好习惯。
推荐阅读
- angular - 角度监听启用/禁用元素
- sql-server - 在混合模式下使用 PowerShell 脚本复制 SQL Server 数据库
- c# - DataGridView 中彩色单元格的计数
- openmpi - 我如何在 Slurm 下运行 Open MPI
- java - 无法使用 getFileDir 将图像保存到 Android 中的照片/图库
- xpath - xsl
: 如何选择一个有某个孩子的兄弟姐妹? - android - 如何解决 Google API 建议、程序类型已经存在的问题?
- python - Django - 在提交表单时分配外键
- airflow - AirFlow - 在 X 次连续失败后禁用 dag
- openbravo - 如何让最新的 Openbravo ERP 工作?找不到起点