[英]Make a component Rerender on useEffect
我正在創建一個搜索欄,它調用 API 以返回具有匹配名稱的設備列表。 理想情況下,當用戶第一次查看組件時,它只會看到一個搜索欄。 一旦用戶在搜索欄中鍵入內容,API 就會返回匹配名稱的列表。 然后在搜索欄下方顯示這些名稱的列表。
我正在嘗試使用鈎子來執行此操作,但無法獲取要顯示的列表/要更新的組件並顯示新列表。
我錯過了什么,這是解決這個問題的正確方法嗎?
const Search = () => {
const [input, setInput] = useState("");
let devices = [];
const handleChange = e => {
setInput(e.target.value.toUpperCase());
};
useEffect(() => {
apiService.getDevices(input).then(response => {
console.log("response:", response); // This brings back the response correctly
const newDevices = response.map(device => <li key={device}>{device}</li>);
devices = <ul>{newDevices}</ul>;
});
}, [input]);
return (
<Fragment>
<div>
<div className="form-group">
<div className="form-group__text">
<input
type="search"
onChange={handleChange}
placeholder="Search device by serial number"
/>
<button type="button" className="link" tabIndex="-1">
<span className="icon-search"></span>
</button>
</div>
</div>
<div>{devices}</div>
<p>testestes</p>
</div>
</Fragment>
);
};
將設備存放在 state 中,然后直接在 return 中進行地圖渲染,如下所示:
const Search = () => {
const [input, setInput] = useState("");
const [devices, setDevices] = useState([]);
const handleChange = e => {
setInput(e.target.value.toUpperCase());
};
useEffect(() => {
apiService.getDevices(input).then(response => {
setDevices(response);
});
}, [input]);
return (
<Fragment>
<div>
<div className="form-group">
<div className="form-group__text">
<input
type="search"
onChange={handleChange}
placeholder="Search device by serial number"
/>
<button type="button" className="link" tabIndex="-1">
<span className="icon-search"></span>
</button>
</div>
</div>
<div>
<ul>
{devices.map(device => <li key={device}>{device}</li>)}
</ul>
</div>
<p>testestes</p>
</div>
</Fragment>
);
};
組件只會在 props 或 state 改變時重新渲染,所以useEffect
不能在不更新某些狀態的情況下觸發重新渲染
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.