【发布时间】:2021-02-28 18:22:27
【问题描述】:
当我输入搜索词(姓名、电子邮件、用户名)时,我希望页面根据搜索值从所有卡片中过滤出一张卡片。我想当用户按下回车键时,我们需要重定向到一个新页面来显示卡片。
我有搜索栏的代码和负责显示单个用户卡的用户组件。我们是否需要使用 react-router 的 Redirect 功能来实现这一点?我一直在为如何实现它而苦苦挣扎,因为道具(searchItem)也需要传递给用户组件。
搜索栏.jsx
import React, { useState } from "react";
import UserList from "./UserList";
import User from "./Components/User";
import { Link, Redirect } from "react-router-dom";
const SearchBar = () => {
const [searchItem, setSearchItem] = useState("");
const handleChange = (e) => {
console.log(e.target.value);
setSearchItem(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
setSearchItem("");
};
return (
<>
<div className="searchbar">
<form onSubmit={handleSubmit}>
<input
name="name"
placeholder="Enter Name, Email or Username to Search"
type="text"
className="search"
value={searchItem}
onChange={handleChange}
/>
</form>
</div>
<UserList />
</>
);
};
export default SearchBar;
用户.jsx
import React from "react";
import Card from "./Card";
const User = (props) => {
return (
<Card
key={props.id}
name={props.name}
email={props.email}
website={props.website}
phone={props.phone}
/>
);
};
export default User;
用户列表.jsx
import React, { useState, useEffect } from "react";
import Card from "./Components/Card";
const UserList = ({ searchItem }) => {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((json) => {
console.log(json);
const newData = json.map((object) => ({
id: object.id,
email: object.email,
website: object.website,
phone: object.phone,
name: object.name,
}));
// previousData is an empty array and the newData consists of all the users
// using the spread operator, we copy the newData into the previousData
setData((previousData) => [...previousData, ...newData]);
});
}, []);
return (
<>
<div className="container">
{data.map((info) => {
return (
<Card
key={info.id}
name={info.name}
email={info.email}
website={info.website}
phone={info.phone}
/>
);
})}
</div>
</>
);
};
export default UserList;
【问题讨论】:
标签: javascript reactjs react-router