首页 > 解决方案 > React Hook 在 useEffect 中设置状态与依赖数组中的状态

问题描述

我有一个关于在 React Hooks 中正确使用 useEffect 和 setState 的问题。

这是我的反应应用程序,它根据如下配置获取持久配置和一些其他数据:

function App() {
    const [config, setConfig] = useState(null);
    // some other states 

    useEffect(() => {
        const fetchData = () => {
            axios.get("/path/to/config").then(response => {
                if (response.status === 200) {
                    return response.data
                }
            })
                .then(data => {
                    setConfig(data.config);
                    // set some other states
                })
                .catch(error => {
                    console.log("Error:" + error);
                })
        }
        fetchData();
    }, [config]);

    return (
        <div >
            ...
        </div>
    );
}

如果我运行这个应用程序 useEffect 会立即调用两次,第一次渲染,然后第二次,因为setConfig(data.config);在 axios get success 函数中调用。

用户可以更改在另一个请求中完成的自己的配置。如果他确实想要在状态配置更改后通过此 useEffect 函数重新加载配置和其他一些取决于配置的数据。

现在,由于反应钩子中没有 setstate 回调,我在某处读到我应该使用 useEffect 和依赖数组中的状态变量。

如何防止我的 useEffect 在开始时被调用两次?

我有一种感觉,我做错了。先感谢您

标签: reactjsreact-hooks

解决方案


您需要在 useEffect 中添加一个 if 条件,因为在第一次渲染时默认调用 useEffect。

useEffect(() => {
      if(config !== null){
        const fetchData = () => {
            axios.get("/path/to/config").then(response => {
                if (response.status === 200) {
                    return response.data
                }
            })
                .then(data => {
                    setConfig(data.config);
                    // set some other states
                })
                .catch(error => {
                    console.log("Error:" + error);
                })
        }
        fetchData();
      }
    }, [config]);

推荐阅读