如何包装到act(...)秒/延迟/异步渲染 [英] How to wrap into act(...) second/deferred/async rendering
本文介绍了如何包装到act(...)秒/延迟/异步渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下组成部分:
function MyComp(props) {
const [items, setItems] = useState([]);
useEffect(() => { loadItems(); }, []);
async function loadItems() {
const result = await axios.get(`https://example.com/api`);
setItems(result.data);
}
return (<div>{items.map(item => ...)}</div>);
}
此测试会产生行为警告:
And this test produces the act warning:
const items = { "data": [{"id": 1, "title": "Title1"}] };
axios.get.mockImplementationOnce(() => Promise.resolve(items));
const wrapper = mount(<MyComp />);
警告:测试中MyComp的更新未包含在act(...)中.
Warning: An update to MyComp inside a test was not wrapped in act(...).
据我了解,发生这种情况的原因是第二次更新了获取的项目.如何解决这个问题?
From what I understand this happens because of the second update with fetched items. How to solve this issue?
这有帮助
let wrapper = null;
await act(async () => {
wrapper = mount(<MyComp />);
});
推荐答案
您尝试过吗?
import { act } from 'react-dom/test-utils';
//...
let wrapper = null;
act(() => {
wrapper = mount(<MyComp />);
});
在这里您可以找到更多信息 https://reactjs.org/docs /testing-recipes.html#act
here you can find more info https://reactjs.org/docs/testing-recipes.html#act
这篇关于如何包装到act(...)秒/延迟/异步渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文