Javascript 如何防止类型错误:无法读取属性';地图';提交空表单数据时的未定义值?
好的,所以我的代码工作得很好,但是当我在输入字段为空的情况下点击submit时,我的.map方法没有要添加到要搜索的API字符串末尾的输入值,因此我得到一个typeError:cannot read property of map undefined。因为输入是我的状态,如果我没有在输入字段中输入字符串,那么状态不会得到更新,因此.map方法没有可关闭的更新状态。 那么,如何设置输入字段以要求在提交按钮调用函数“SearchApi”之前输入文本呢?Javascript 如何防止类型错误:无法读取属性';地图';提交空表单数据时的未定义值?,javascript,reactjs,forms,conditional-statements,Javascript,Reactjs,Forms,Conditional Statements,好的,所以我的代码工作得很好,但是当我在输入字段为空的情况下点击submit时,我的.map方法没有要添加到要搜索的API字符串末尾的输入值,因此我得到一个typeError:cannot read property of map undefined。因为输入是我的状态,如果我没有在输入字段中输入字符串,那么状态不会得到更新,因此.map方法没有可关闭的更新状态。 那么,如何设置输入字段以要求在提交按钮调用函数“SearchApi”之前输入文本呢? 我试图设置条件,但它似乎不起作用……比如……如
我试图设置条件,但它似乎不起作用……比如……如果input.length<1{setInput(“E.T”),那么它就有东西可以搜索,并且不会返回错误。我也在网上查看react表单验证教程,但我觉得可能我在这方面完全错了。任何帮助都会很感激的,谢谢
import React, {useState, useEffect} from 'react';
const SearchBar = () => {
const [search, setSearch] = useState([]);
const [input, setInput] = useState('');
const [trending, setTrending] = useState([]);
const [upcoming, setUpcoming] = useState([]);
// Input Field
const onUserInput = ({target}) => {
setInput(target.value);
}
// Api Call
const SearchApi = (event) => {
const aUrl = "https://api.themoviedb.org/3/search/movie?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
const newUrl = aUrl +'&query=' + input;
event.preventDefault();
fetch(newUrl)
.then((response) => response.json())
.then((data) => {
setSearch(data.results);
})
.catch((error) => {
console.log('Error!! Data interupted!:', error)
})
}
return (
// Heading
<div>
<div className="container">
<h1>Movie Search Extravaganza!</h1>
{/* Input Field and Button Form */}
<form>
<input value={input} onChange={onUserInput} type="text" className="searchbar" aria-label="searchbar" placeholder="search" name="movie" required/>
<br></br>
<button type="submit" onClick={SearchApi} aria-label="searchbutton" className="searchBtn">Movie Express Search</button>
</form>
</div>
<div className="byName-container">
<h1 className="row-label" tabIndex="0">Movies Related To Your Search</h1>
<ul className="flexed-search">
{search.map((item) =>
<div className="poster-container">
<li className="list-item" key={item.id}>
<img className="image-element" tabIndex="0" alt="movie poster" aria-label={item.title} src={`https://image.tmdb.org/t/p/w500${item.poster_path}`} />
<h3 className="posterTitle">{item.title}</h3>
</li>
</div>
)}
</ul>
</div>
<div className="trending-container">
<h1 className="row-label" tabIndex="0">This Weeks Trending Tittles</h1>
<ul className="flexed-trending">
{trending.map((it) =>
<div className="poster-container">
<li className="list-item" key={it.id}> <img className="image-element" tabIndex="0" aria-label={it.title} alt="movie poster" src={`https://image.tmdb.org/t/p/w500${it.poster_path}`} />
<h3 className="posterTitle">{it.title}</h3>
</li>
</div>
)}
</ul>
</div>
<div className="upcoming-container">
<h1 className="row-label" tabIndex="0">Upcomming Movies</h1>
<ul className="flexed-upcoming">
{upcoming.map((inn) =>
<div className="poster-container">
<li className="list-item" key={inn.id}>
<img className="image-element" tabIndex="0" alt="movie poster" aria-label={inn.title} title={`${inn.title}: ==> ${inn.overview}`} src={`https://image.tmdb.org/t/p/w500${inn.poster_path}`} />
<h3 className="posterTitle">{inn.title}</h3>
</li>
</div>
)}
</ul>
</div>
</div>
)
};
export default SearchBar;```
import React,{useState,useffect}来自“React”;
常量搜索栏=()=>{
const[search,setSearch]=useState([]);
const[input,setInput]=useState(“”);
常量[trending,setTrending]=useState([]);
const[coming,setUpcoming]=useState([]);
//输入字段
常量onUserInput=({target})=>{
设置输入(目标值);
}
//Api调用
const SearchApi=(事件)=>{
const aUrl=”https://api.themoviedb.org/3/search/movie?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
const newUrl=aUrl+'&query='+input;
event.preventDefault();
获取(新URL)
.then((response)=>response.json())
。然后((数据)=>{
setSearch(数据、结果);
})
.catch((错误)=>{
console.log('错误!!数据中断!:',错误)
})
}
返回(
//标题
电影搜索盛典!
{/*输入字段和按钮表单*/}
电影快车搜索
与您的搜索相关的电影
{search.map((项目)=>
-
{item.title}
)}
本周流行的标题
{trending.map((it)=>
-
{it.title}
)}
上流电影
{即将到来的.map((inn)=>
-
{inn.title}
)}
)
};
导出默认搜索栏```
您在表单中犯了一个小错误
更改此项:
<form>
...
<button type="submit" onClick={SearchApi} aria-label="searchbutton" className="searchBtn">
Movie Express Search
</button>
</form>
...
电影快车搜索
作者:
...
电影快车搜索
输入的“必需”将起作用。演示:
PS:检查所有地图功能中的键
{search.map(item => (
<div className="poster-container"> //pass the key here and do the same for others
<li className="list-item" key={item.id}>
{search.map(项=>(
//把钥匙传给这里,其他人也一样
您可以尝试使用
required={true}
验证表单的方法有很多,这有点取决于您使用的样式。但是如果我理解正确,您会尝试在SearchApi函数中更新输入值,如果其为空
if input.length<1{setInput(“E.T”)}
?无论何时更新状态,它都是异步的,这意味着如果您试图将更新后的输入发送到url,那么它仍将使用setState调用之前的旧值。因此,基本上,如果setInput是用空字符串初始化的。然后我尝试在上面的OnUserInput函数中设置条件,我是否能够o使用“if-input.length<1{setInput(“E.T”)}”else-setInput(target.value)?就像说如果输入字段中没有输入文本,则将状态更新为“E.T”?或者将状态更新为target.value?我只是用这种方式来防止用户点击提交时出现错误。如果你能解释另一种方式,我会非常感兴趣听到它,我现在对如何处理这件事很迷茫。“必需”这就足够了,不需要条件函数,只要看看我的答案就可以了。但是如果你在输入值为空时将其更改为E.T,那么它也会将输入字段更改为E.T,这可能会让用户感到困惑。最好和最简单的方法可能是执行类似MB_ugest的操作。但是如果你出于某种原因想在SearchApi您可以始终使用私有变量:let queryInput=input.length>=1?输入:“E.T”
和const newUrl=aUrl+”&query=“+queryInput;”required={true}和required它是相同的(默认情况下为true)谢谢你,MB_u,这很好地解决了关键点,因此如果我将关键点添加到容器div而不是li项,它将覆盖所有内容?是的!你总是将关键点放在地图的第一个元素中,这将覆盖所有内容
required={true}