调用 REST API 在首次显示组件时的最佳实践是什么?

huangapple go评论66阅读模式
英文:

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)
    },[])

huangapple
  • 本文由 发表于 2023年2月26日 22:51:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定