英文:
What is the best practice for calling a REST API when a component is shown for the first time?
问题
请尝试以下代码以确保thunk仅执行一次:
useEffect(() => {
if (state.length === 0) {
dispatch(fetchList);
}
}, []);
这段代码中,我们使用了useEffect
来执行dispatch(fetchList)
,但仅当state
的长度为0时(即,ToDo项的列表为空时)执行。通过将空的ToDo列表长度与0进行比较,您可以确保fetchList
仅在组件首次渲染时触发。将[]
作为useEffect
的第二个参数,以确保它只在组件挂载时运行一次。这是确保thunk只执行一次的一种最佳实践方式。
英文:
Let's say I am implementing a simple ToDo list in React Native, where the list is stored remotely via a REST API.
Let's say I have a GET /list
endpoint to fetch the list of ToDo items.
Now let's say I have a component, defined as a function, to render the list:
function TodoList(): JSX.Element {
// Use selector gets a value out of the state
const state: State = useSelector((state: any) => state.list);
// Use dispatch gives us a handle to dispatch actions
const dispatch = useDispatch();
return (<View>
// .. render the list htere
</View>)
}
Let's say I also have a thunk defined which fetches the list:
export const fetchList = (dispatch: any, getState: any) => {
dispatch(setListFetchState(FetchState.Fetching))
fetch(`http://{HOST}/item`)
.then(response => response.json())
.then((result) => {
dispatch(setListData(result))
})
}
}
So the behavior I want is: the first time the TodoList component is rendered, it should dispatch fetchList
in order to load the initial data from the API.
How can I achieve this?
I have tried inserting:
useEffect(() => {
dispatch(fetchList)
})
inside my component function, but this seems to result in fetchList
being dispatched in an infinite loop.
What is the best practice for ensuring that this thunk is only executed once?
答案1
得分: 1
你没有添加任何依赖项。
useEffect(() => {
dispatch(fetchList);
})
这意味着每次组件重新渲染时,这个 useEffect
都会运行。由于你正在向 Redux 存储分发一个操作,改变状态会导致重新渲染,因此 useEffect
会再次运行。
因为你希望它只在第一次运行,所以你需要添加一个空数组作为依赖项。
useEffect(() => {
dispatch(fetchList);
}, [])
英文:
you did not add any dependency
useEffect(() => {
dispatch(fetchList)
})
this means every time your component rerenders, this useEffect
will run. and since you are dispatching an action to redux store, changing the state, will cause a rerender, so useEffect
will re run again
since you want the first time it runs, you need to add an empty array as a dependency
useEffect(() => {
dispatch(fetchList)
},[])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论