reactjs - 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 在开始时被调用两次?
我有一种感觉,我做错了。先感谢您
解决方案
您需要在 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]);
推荐阅读
- python - 如何在python中打开csv?
- tensorflow - Keras - K.print 在损失函数中不起作用
- mysql - 更新 MariaDB 后如何停止 XAMPP 的 MySQL 服务
- node.js - How do i get nested schema keys from mongoose main model?
- scala - Heroku 的 Akka 应用程序出现错误:Web 进程无法绑定到 $PORT
- javascript - OT 未定义?
- wordpress - login_message 不显示 WordPress 5.1.1
- c# - 用于空检查的“is”类型模式表达式
- java - 处理数组时如何同时使用 Java 和 Groovy 语法?
- karate - 如果预期数量较大,空手道不会检查案例,我该如何处理?