Javascript 在React中设置useState中的输入值

Javascript 在React中设置useState中的输入值,javascript,reactjs,use-state,Javascript,Reactjs,Use State,我试图通过onChange事件中下面的useState()hook设置一些输入值,并希望在authord中获取作者id。但是,当Iconsole.log()newObj放入值后,会设置其他每一个变量,但auhtorId将作为其初始状态返回,该状态为空字符串。你能告诉我我做错了什么吗 import React,{useState} from 'react' import { useQuery } from '@apollo/client'; import {AuthorsQuery }from '

我试图通过
onChange
事件中下面的
useState()
hook设置一些输入值,并希望在authord中获取作者id。但是,当I
console.log()
newObj放入值后,会设置其他每一个变量,但auhtorId将作为其初始状态返回,该状态为空字符串。你能告诉我我做错了什么吗

import React,{useState} from 'react'
import { useQuery } from '@apollo/client';
import {AuthorsQuery }from '../queries/Queries'


 export const AddBook = () => {



const [name, setName]= useState('');
const [genre, setGenre]= useState('');
const [authorId, setauthorId]= useState('');





const  logSubmit = (event)=>{
   
    event.preventDefault();
    const newObj = {name,genre,authorId}
    console.log(newObj)
  }

 

const { loading, error, data } = useQuery(AuthorsQuery);

if (loading) return <p>Loading...</p>;
 if (error) return <p>Error :(</p>;

 console.log(data);






 

  return (
    
    <form id="add-book" onSubmit={logSubmit}>
    <div className="field">
        <label>Book name:</label>
        <input type="text" value={name} onChange={(e)=> setName( e.target.value)} />
    </div>
    <div className="field">
        <label>Genre:</label>
        <input type="text" value={genre} onChange={(e)=> setGenre(e.target.value)} />
    </div>
    <div className="field">
        <label>Author:</label>
                  <select onChange={(e)=>setauthorId(e.target.key)} value= 
    {author.id } >
             <option disabled>Select Author</option>
             
                 {data.authors.map(author =>(
                      <option  key={author.id}  >{author.name} </option>
                     
                 ) )
                
  }
         
       
           
            
        </select> 
        

    </div>
    <button >+</button>

  </form>
  )
 }
import React,{useState}来自“React”
从'@apollo/client'导入{useQuery};
从“../querys/querys”导入{AuthorsQuery}
导出常量AddBook=()=>{
const[name,setName]=useState(“”);
const[genre,setGenre]=useState(“”);
const[authorId,setauthorId]=useState(“”);
const logSubmit=(事件)=>{
event.preventDefault();
const newObj={名称、流派、作者}
console.log(newObj)
}
const{loading,error,data}=useQuery(AuthorsQuery);
如果(加载)返回加载…

; if(error)返回错误:(

; 控制台日志(数据); 返回( 书名: setName(e.target.value)}/> 体裁: setgreen(e.target.value)}/> 作者: setauthorId(e.target.key)}值= {author.id}> 选择作者 {data.authors.map(author=>( {author.name} ) ) } + ) }
按setauthorId更改setauthorId(用于useState和onChange)

我认为这只是一个惯例错误,问题描述中没有要做的事情,尽管我按照你说的做了,但是没有用。是的,当然,你可以在你的选择字段中更改:e.target.key by e.target.value。是的,我也这样做了,但这一次它给出了作者没有定义,因为映射在选项中,我正在应用onC在选择框中挂起。