Srd*_*No1 7 fetch reactjs react-hooks
有人问过类似的问题,但我还没有找到针对这个特定问题的解决方案。我有一个组件可以渲染所有板,我正在使用自定义useFetch钩子来获取所有板。
const BoardsDashboard = () => {
let [boards, setBoards] = useState([]);
const { response } = useFetch(routes.BOARDS_INDEX_URL, {});
setBoards(response);
return (
<main className="dashboard">
<section className="board-group">
<header>
<div className="board-section-logo">
<span className="person-logo"></span>
</div>
<h2>Personal Boards</h2>
</header>
<ul className="dashboard-board-tiles">
{boards.map(board => (
<BoardTile title={board.title} id={board.id} key={board.id} />
))}
<CreateBoardTile />
</ul>
</section>
</main>
);
};
const useFetch = (url, options) => {
const [response, setResponse] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
return { response, error };
};
Run Code Online (Sandbox Code Playgroud)
由于setBoards(response)线路的原因,我得到了太多的重新渲染,但我不确定处理这个问题的正确方法是什么。
谢谢!
Nic*_*ick 14
听起来您可能希望 useEffect 钩子在响应更新时采取行动。
useEffect(() => {
setBoards(response);
}, [response]);
Run Code Online (Sandbox Code Playgroud)
注意:如果您不需要更改boards状态,那么也许它根本不需要是有状态的,您可以使用useFetch钩子的返回值并完成它。
const { response: boards } = useFetch(...);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15661 次 |
| 最近记录: |