6

在我的许多组件中,我必须使用商店中的令牌来获取数据并表示它(页眉菜单、页脚菜单、页面上的产品、滑块图像等)。我想要做的是仅在我没有它的情况下获取这些数据,但是 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]);
4

2 回答 2

2

无论如何,第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回调:

const token = useMemo(() => props.token, []);
于 2019-11-27T18:13:15.467 回答
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)。

于 2019-11-27T18:14:00.070 回答