小编And*_*mdt的帖子

测试异步 useEffect

我的功能组件使用useEffect钩子从挂载的 API 中获取数据。我希望能够测试获取的数据是否正确显示。

虽然这在浏览器中工作正常,但测试失败了,因为钩子是异步的,组件没有及时更新。

活码:https : //codesandbox.io/s/peaceful-knuth-q24ih?fontsize=14

应用程序.js

import React from "react";

function getData() {
  return new Promise(resolve => {
    setTimeout(() => resolve(4), 400);
  });
}

function App() {
  const [members, setMembers] = React.useState(0);

  React.useEffect(() => {
    async function fetch() {
      const response = await getData();

      setMembers(response);
    }

    fetch();
  }, []);

  return <div>{members} members</div>;
}

export default App;
Run Code Online (Sandbox Code Playgroud)

App.test.js

import App from "./App";
import React from "react";
import { mount } from "enzyme";

describe("app", () => { …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs enzyme

13
推荐指数
3
解决办法
1万
查看次数

导出上下文不适用于 contextType

我有一个文件App.js,从中默认导出一个 React 组件。除此之外,同一个文件导出了一个 React Context。

在子组件中使用 Context 时(使用static contextType = Context),我只会收到以下警告:

Warning: Versions defines an invalid contextType. contextType should point to the Context object returned by React.createContext(). However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file.
Run Code Online (Sandbox Code Playgroud)

this.context 也是未定义的。

但是,在 render 方法中使用消费者效果很好:

<Context.Consumer>{({ name }) => …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs

4
推荐指数
1
解决办法
1236
查看次数

标签 统计

javascript ×2

reactjs ×2

enzyme ×1

jestjs ×1