【问题标题】:React useEffect Hook not Triggering on First Render with [] DependenciesReact useEffect Hook 不会在具有 [] 依赖项的第一次渲染时触发
【发布时间】:2020-12-11 22:47:28
【问题描述】:

我通过 Axios GET 请求从本地 API 获取数据并尝试将数据保存在上下文对象中。

当我在 Context Provider 函数之外运行 GET 请求时,它可以正常工作。 但是当我将它放在没有依赖关系的 UseEffect 函数中时 - 即。 useEffect( () => /* do something*/, [] )useEffect 钩子永远不会触发。

代码在这里:

import React, { createContext, useReducer, useEffect } from 'react';
import rootReducer from "./reducers";
import axios from 'axios';
import { GET_ITEMS } from "./reducers/actions/types";

export const ItemsContext = createContext();

function ItemsContextProvider(props) {
  const [items, dispatch] = useReducer(rootReducer, []);
  
  console.log('this logs');
  useEffect(() => {
    console.log('this does not');
    axios.get('http://localhost:27015/api/items')
      .then(data => dispatch({type: GET_ITEMS, payload: data}))
  }, [])

  return (
    <ItemsContext.Provider value={{items, dispatch}}>
      { props.children }
    </ItemsContext.Provider>
  );
}

export default ItemsContextProvider;

我从未在控制台中看到“这不是”(双重和三重检查)。我首先尝试将上下文初始化为空值,在第一次渲染时发出 GET 请求,然后更新上下文值。

如果我做错了什么,我真的很感激。


编辑 - 呈现上下文提供者的位置

import React from 'react';
import AppNavbar from "./Components/AppNavbar";
import ShoppingList from "./Components/ShoppingList";
import ItemModal from "./Components/ItemModal";
//IMPORTED HERE (I've checked the import directory is correct)
import ItemsContextProvider from "./ItemsContext"; 
import { Container } from "reactstrap"

import "bootstrap/dist/css/bootstrap.min.css";
import './App.css';

function App() {
  return (
    <div className="App">
    <ItemsContextProvider> //RENDERED HERE
      <AppNavbar />
      <Container>
        <ItemModal />
        <ShoppingList /> //CONSUMED HERE
      </Container>
    </ItemsContextProvider>
    </div>
  );
}

export default App;

我在另一个具有以下 sn-p 的文件中使用它:

const {items, dispatch} = useContext(ItemsContext);
console.log(items, dispatch);

我看到控制台日志显示了我在 Context Provider 中的 useEffect 函数之外初始化的空数组,以及对调度函数的引用。

【问题讨论】:

  • 即使像 useEffect( () =&gt; console.log('test'), [] ); 这样的东西也不会将任何内容记录到控制台
  • 如果您在 useEffect 之外但在组件内使用 console.log,您会看到任何日志吗?
  • 你能把代码贴在你渲染&lt;ItemsContextProvider&gt;的地方吗?
  • @Mr.Robot 是的。我已经更新了我原来帖子中的 sn-p 来证明这一点。
  • 谢谢!看起来你已经正确设置了它,我会尝试删除或注释掉其他代码,直到你尽可能简单,隔离问题。你能在 CodeSandbox 上制作一个可重现的版本吗?

标签: javascript reactjs react-hooks use-effect context-api


【解决方案1】:

&lt;ItemsContextProvider /&gt; 未呈现。

确保正在被另一个 jsx 父元素使用和呈现。

【讨论】:

  • 我现在已经发布了上面的代码,它在 App.js 中呈现(React 导入,所以 jsx 应该可以工作)。上下文提供程序中的代码是否需要在另一个文件中使用才能工作?我在另一个文件中使用了它,该文件具有以下 sn-p:const {items, dispatch} = useContext(ItemsContext); console.log(items, dispatch); /b>
猜你喜欢
  • 1970-01-01
  • 2020-01-23
  • 2020-12-23
  • 2021-02-23
  • 2022-11-23
  • 1970-01-01
  • 2020-10-26
  • 2019-10-24
  • 2020-07-24
相关资源
最近更新 更多