【发布时间】:2021-09-15 12:25:52
【问题描述】:
我正在使用来自用户的关键字在我的数据库中搜索用户。我将值保持在我的状态并尝试在 onChnge() 事件上调用 API,但它冻结了我的输入字段,我无法在输入字段中添加或删除字符,我在 onChange() 之后立即调用 API,
我尝试了 onSubmit 它的魅力,但我想在每次击键时调用 API。
const CardAddChat = () => {
const initialState = {
private: true,
search: "",
usersList: [],
selectedPersons: [],
};
const [state, setState] = useState(initialState);
const handleChange = (e) => {
setState({ ...state, search: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
let res = await axios.get(`/api/users?term=${state.search}`);
setState({ ...state, usersList: res.data.data });
} catch (error) {
console.error(error);
}
};
const handleGroupChange = () => {
setState({ ...state, private: !state.private });
};
return (
<>
<div className=" w-96 flex flex-col bg-blueGray-200 ">
<h1 className="text-2xl p-3 border-b">
{state.private ? "New Private Chat" : "New Group Chat"}
</h1>
<div className="flex-none pb-2 ">
<form
onSubmit={handleSubmit}
class="pt-2 relative mx-auto w-full px-2 text-gray-600 flex items-center"
>
<input
class="px-3 bg-white h-10 rounded-full text-xs focus:outline-none w-full pr-10"
type="search"
name="search"
value={state.search}
onChange={handleChange}
placeholder="Search for messages or users.."
/>
这里是临时的,我正在调用 API onSubmit,但有任何方法可以让它在 onChange 触发。 提前致谢。
【问题讨论】:
标签: reactjs api async-await state onchange