![](/img/trans.png)
[英]Change of state is not getting affected in another unmount useEffect in react hooks
[英]React Hooks Wrapper not getting updated after state change in useEffect
當前行為
我在useEffect
使用了一個帶有setState
鈎子的功能組件。 在useEffect
設置的狀態變量被包裝在 return 語句中以呈現組件的 JSX。
當我調試它時,組件使用正確的狀態變量呈現,但我的測試中的包裝器沒有顯示正確的信息。
wrapper.update()
沒有解決這個問題。
下面是我試圖實現的一個片段:
const DummyComponent= ({}) => {
const [selected, setSelected] = React.useState(false);
useEffect(() => {
setSelected(true)
}, [someDependency])
return (
{
selected && (
<div id= 'container'>
{childComponents}
</div>)
}
);
})
it('test', () => {
const wrapper= mount( <DummyComponent /> );
wrapper = wrapper.update(); // this doesn't fix my problem
wrapper.find('#container')first().props().onClick();
expect(wrapper.toMatchSnapshot());
});
我收到以下錯誤:
Method “props” is meant to be run on 1 node. 0 found instead.
預期行為
在useEffect
狀態更新之后,應該在測試用例中觸發重新渲染,並且應該找到id="container"
元素。
在我看來,您的真實代碼還存在其他問題(也許在效果中調用了一些基於 Promise 的代碼?)。 這是一個基於您的代碼段的工作示例:
const DummyComponent = ({}) => {
const [selected, setSelected] = React.useState(false);
const [result, setResult] = React.useState("");
React.useEffect(() => {
setSelected(true);
}, []);
return selected && <div id='container' onClick={() => setResult("test")}>
<label>{result}</label>
</div>;
};
it('test', () => {
const wrapper = mount(<DummyComponent/>);
act(() => {
wrapper.find('#container').first().props().onClick();
});
expect(wrapper.find("label").text()).toEqual("test");
});
該act
實際上僅用於與組件本身的交互,而不是渲染后的效果。
問題是當你第一次掛載組件時,它不會渲染任何東西,因為selected
是 false。 因此,當您搜索'#container'
,您什么也得不到。
如果update
足夠了,那么它可能應該在wrapper.find()
之前執行,以便組件以selected
true 呈現。 但是 React 是異步的,我懷疑這還不夠……
我解決了我的問題,實際上我需要將我的組件分配給不同的包裝器,然后更新包裝器,然后檢查包裝器而不是組件上的更新。 下面是片段:
it('test', () => {
const component= mount( <DummyComponent /> );
const wrapper = component.update();
wrapper.find('#container')first().props().onClick();
expect(wrapper.toMatchSnapshot());
});
這將具有更新的組件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.