useEffect与React Hooks进入无限循环

时间:2019-04-21 13:59:43

标签: javascript reactjs react-hooks

在将useEffect与对象引用一起使用时,React / Redux应用程序进入无限循环。

我正在尝试使用useEffect ..为我的应用程序渲染待处理的待办事项,并将待办事项数组作为useEffect中的第二个参数传递..但是为什么不检查对象的值呢? / p>

容器:

const mapDispatchToProps = dispatch => ({ actions: bindActionCreators(RootActions, dispatch) });
const Home = (props) => {
  const { root, actions } = props;

  useEffect(() => {
    getTodos(actions.loadPendingTodo);
  }, [root.data]);

  return (
    <Segment>
      <Error {...root } />
      <TodoList { ...root } actions={actions} />
  </Segment>
  );
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);

操作:

export const loadPendingTodo = () => ({
  type: LOAD_PENDING_TODO,
  data: todoService.loadPendingTodo(),
});

异径管:

const initialState = {
  initial: true,
  data: [{
    id: 0,
    text: 'temp todo',
    dueDate: new Date(),
    completedDate: '',
    isDeleted: false,
    isCompleted: false,
  }],
  error: false,
  isLoading: false,
  isEdit: false,
};

export default function root(state = initialState, action) {
  switch (action.type) {
    case LOAD_PENDING_TODO:
      return {
        ...state,
        data: [...action.data],
      };
...

    default:
      return state;
  }
}

getTodos方法:

export const getTodos = (loadTodo) => {
  try {
    loadTodo();
  } catch (error) {
    console.log(error); // eslint-disable-line
  }
};

服务:

export default class TodoAppService {
  loadPendingTodo() {
    return store.get('todoApp').data.filter(todo => !todo.isCompleted && !todo.isDeleted);
  }

任何人都可以帮助我解决该问题的方法吗。.并且也没有官方文件说明此情况:/

此外,将useEffect更改为以下作品,但我想在每次更改时进行渲染

  useEffect(() => {
    getTodos(actions.loadPendingTodo);
  }, []);

1 个答案:

答案 0 :(得分:0)

通过删除loadPedningTodo中导致其循环的useEffect redux操作并直接从服务中设置数据来解决此问题。

const Home = (props) => {
  const { root, actions } = props;
  return (
    <Segment>
      <Error {...root } />
      <TodoList isEdit={root.isEdit} todo={todoService.loadPendingTodo()} actions={actions} />
  </Segment>
  );
};

谢谢:)