首页 > 解决方案 > 如何让查询结果显示到屏幕上

问题描述

我开发了一个搜索引擎,可以将输入的结果查询到控制台。但是我希望结果显示在屏幕上。不要太担心变量的名称,我现在正在更新它们。我试图遍历我的状态,但每次单击输入时都会导致错误。表单显示完美,但是当我单击输入时页面崩溃。

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

标签: reactjs

解决方案


你得到什么错误?您可能希望useState为您的表单和结果使用不同的。

您正在更改用户状态的数据类型。它被初始化为一个数组,但设置为 中的一个对象handleChanges,我假设返回到 中的一个数组handleSubmit。不知道这是否是一个原因,但这不是一个好习惯。


推荐阅读