我正在构建一个简单的应用程序,用于从电影数据库中搜索电影。搜索输入成功地获取并将apiData设置为具有相同值的电影。
我正在努力绘制和显示电影的标题,并得到错误apiData.map不是一个功能
数据是状态数据是对象的数组。
我想从对象访问标题,即CCD_ 1并显示。
这是代码
const SearchPage = () => {
const [apiData, setApiData] = useState({ results: {} });
const [searched, setSearched] = useState([]);
const [loading, setLoading] = useState(false);
const handleSearch = (event) => {
setSearched(event.target.value);
};
useEffect(() => {
setLoading(true);
fetchSearched(searched).then((data) => setApiData(data.results));
setLoading(false);
}, [searched]);
return (
<>
<form className='search-form'>
<input
type='text'
placeholder='search for a film'
onChange={(event) => handleSearch(event)}
/>
</form>
// code below causes error when un-commented
{/* <SearchList apiData={apiData} /> */}
</>
);
};
const SearchList = ({ apiData }) => {
return (
<div className='search-list'>
SEARCH LIST
<ul>
{apiData.map((movie) => {
return <SearchItem movie={movie} key={movie.id} />;
})}
</ul>
</div>
const SearchItem = ({ movie }) => {
return (
<div className='search-item'>
<li>{movie.title}</li>
</div>
API的映射数据一直让我感到困惑,所以任何澄清都将不胜感激。
因为您设置了apiData的初始数据是对象。请参考我的代码:
const SearchPage = () => {
const [apiData, setApiData] = useState([]); // change to array
const [searched, setSearched] = useState(""); // i think it is string
const [loading, setLoading] = useState(false);
const handleSearch = (event) => {
setSearched(event.target.value);
};
useEffect(() => {
if(!searched) return
setLoading(true);
fetchSearched(searched).then((data) => {
setApiData(data.results)
setLoading(false);
});
}, [searched]);
return (
<>
<form className='search-form'>
<input
disabled={loading}
type='text'
placeholder='search for a film'
onChange={(event) => handleSearch(event)}
/>
</form>
// code below causes error when un-commented
<SearchList apiData={apiData} />
</>
);
};
const SearchList = ({ apiData = [] }) => {
return (
<div className='search-list'>
SEARCH LIST
<ul>
{apiData.map((movie) => {
return <SearchItem movie={movie} key={movie.id} />;
})}
</ul>
</div>
您的第一行const [apiData, setApiData] = useState({ results: {} });
正在将对象设置为状态。同时,您的api响应正在将一个数组设置为状态。我认为出现错误的原因是读取初始状态的方式,而不是api调用。
我认为,如果您简单地将其更改为const [apiData, setApiData] = useState([]);
,它就会起作用。快乐编码