简体   繁体   English

React Hook useEffect 缺少依赖,使用 Redux

[英]React Hook useEffect has a missing dependency, using Redux

Should I ignore 'React Hook useEffect has a missing dependency' warning?我应该忽略“React Hook useEffect 缺少依赖项”警告吗? Usually when I am getting data from an API this is what I do:通常,当我从 API 获取数据时,我会这样做:

const Component = () => {
  const [data,setData] = useState([]);

  const getData = () => {
    //Getting data and set data code...
  }

  useEffect(()=>{
   getData();
  },[]);
}

and recently I am trying out use redux to do the same thing(getting data from API) and I got this 'React Hook useEffect has a missing dependency' warning...最近我正在尝试使用 redux 做同样的事情(从 API 获取数据),我得到了这个“React Hook useEffect has a missing dependency”警告......

action:行动:

import {GET_POSTS} from './types';

const getPosts = () => (dispatch) => {
    const url = 'https://jsonplaceholder.typicode.com/posts';
    fetch(url)
    .then(res => res.json())
    .then(data => {
        dispatch({
            type: GET_POSTS,
            payload: data
        });
    });
}

export default getPosts;

reducer:减速器:

import {GET_POSTS} from '../actions/types';

const initialState = {
    posts: []
}

const postsReducer = (state = initialState, action) => {
    switch(action.type){
        case GET_POSTS:
            return {
                ...state,
                posts: action.payload
            }
        default:
            return state;
    }
}

export default postsReducer;

app.js:应用程序.js:

import React, {useEffect} from 'react';
import {connect} from 'react-redux';
import Hello from './components/Hello';
import getPost from './actions/postsAction';
import './App.css';

const App = ({getPost, dispatch}) => {
  useEffect(() => {
    getPost();
  },[]);

  return (
    <div className='App'>
      <Hello/>
    </div>
  );
};

const mapdispatchtoprops = (dispatch) => ({
  dispatch,
  getPost: () => {
    dispatch(getPost());
  }
});

export default connect(null, mapdispatchtoprops)(App);

Is there a way to fix this problem, I have tried to put dispatch inside the useEffect array but the warning still shows, like this:有没有办法解决这个问题,我试图将调度放在 useEffect 数组中,但警告仍然显示,如下所示:

  useEffect(() => {
    getPost();
  },[dispatch]);

This is the full warning: React Hook useEffect has a missing dependency: 'getPost'.这是完整的警告: React Hook useEffect 缺少依赖项:'getPost'。 Either include it or remove the dependency array react-hooks/exhaustive-deps要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps

Tried to remove the useEffect array but I'll get infinite loop, it'll just keeps getting the data from the api(I only need it to run once).试图删除 useEffect 数组,但我会得到无限循环,它只会不断从 api 获取数据(我只需要它运行一次)。

Should I ignore the warning?我应该忽略警告吗? if not, whats the best practice way to handle this problem?如果没有,处理这个问题的最佳实践方法是什么?

I never got this kind of warning before when I left the useEffect array empty but got it recently, why?当我将 useEffect 数组留空但最近得到它时,我之前从未收到过这种警告,为什么?

The error message is telling you what you to do.错误消息告诉您要做什么。 Just add getData to the dependencies array like so: [dispatch, getData] .只需像这样将getData添加到依赖项数组中: [dispatch, getData] Anything external you reference within your useEffect (like a function) should be part of the dependency list so it can trigger the effect whenever the value changes.您在useEffect中引用的任何外部内容(如函数)都应该是依赖项列表的一部分,因此它可以在值更改时触发效果。 In your case it likely won't, but React is warning you just to be safe.在你的情况下它可能不会,但 React 警告你只是为了安全。 Hope that helps!希望有帮助!

You may want to start thinking from a different perspective.您可能想从不同的角度开始思考。 You are apparently trying to do side effect of loading data after component got rendered.您显然是在尝试在组件渲染后加载数据的副作用。 So just inject your data via redux or propagation props from parent and remove array altogether.因此,只需通过 redux 或来自父级的传播道具注入您的数据并完全删除数组。 Ie IE

 const Component = ({posts}) => {

  const getData = () => {
    //Getting data and set data code...
  }

  useEffect(() => {
      if (!posts) {
       getData();
      }
  });
  ....
}

Your posts will be loaded once and useEffect's function should only care about posts is there or not.您的帖子将被加载一次,useEffect 的 function 应该只关心posts是否存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM