在我的许多组件中,我必须使用商店中的令牌来获取数据并表示它(页眉菜单,页脚菜单,页面上的产品,滑块图像等)。我想做的是仅在没有数据的情况下获取此数据,但是React每次每次令牌更改时都会发送请求(因为令牌是依赖项),即使我清楚地说明了条件并且可以通过控制台查看到。记录它。我在做什么错了?
const [cities, setCities] = useState([]);
useEffect(() => {
if (!cities.length) {
fetch(`.....&token=${props.token}`)
.then(response => response.json())
.then(data => {
if (data.data.results) {
setCities(data.data.results.cities)
}
})
}
}, [props.token, cities.length]);
答案 0 :(得分:2)
barwidth = 0.35
ggplot() +
geom_bar(data = BUSINESS_18,
mapping = aes(x=Month, y=GWP_mio, fill=Business),
stat ="identity",
position = "stack",
width = barwidth) +
geom_bar(data = BUSINESS_19,
mapping = aes(x=as.numeric(Month) + as.numeric(barwidth) + 0.05, y=GWP_mio, fill=Business),
stat ="identity",
position = "stack",
width = barwidth) +
theme_ipsum() +
scale_fill_manual(values = c("#009E73","Darkblue")) +
scale_y_continuous(breaks=seq(0,18000000,1000000), labels = scales::comma_format(scale = 1/1000000,
accuracy = .1), limits = c(0,18000000)) +
ggtitle('GWP development') +
theme(plot.title = element_text(hjust=0.5, size=14, family="Calibri", face="bold"),
legend.title = element_text(size=11, family="Calibri", face="bold"),
axis.title.x = element_text(hjust=1, size=11, family="Calibri", face="bold"),
axis.text.x = element_text(angle=0, hjust=1, size=11, family="Calibri"),
axis.title.y = element_text(angle=0, hjust=1, size=10, family="Calibri", face="bold"))
在第一次渲染时将为空,因此您无需检查其长度并将其指定为依赖项:
cities
您还可以记住令牌以防止其触发const [cities, setCities] = useState([]);
useEffect(() => {
fetch(`.....&token=${props.token}`)
.then(response => response.json())
.then(data => {
if (data.data.results) {
setCities(data.data.results.cities)
}
})
}, [props.token]);
回调:
useEffect
答案 1 :(得分:0)
//由于评论而被编辑
// should be outside of the function
let timesExecuted = 0
function fetch () {
useEffect(() => {
if(props.token){
timesExecuted = timesExecuted + 1
}
if (timesExecuted === 1) {
fetch(`.....&token=${props.token}`)
.then(response => response.json())
.then(data => {
if (data.data.results) {
setCities(data.data.results.cities)
}
})
}
}, [props.token]);
}
因此,每次仅在prop.token为OKEY时才执行它(可以根据令牌验证随意修改第一个IF)。