Eni*_*via 5 reactjs immer.js react-hooks
我在状态中存储一个节点实体。当我单击按钮时,我想更改属性“标题”,并触发组件更新以显示新的标题值。函数组件中什么也没有发生,它仅在类组件中更新。
类组件:
class ClassTest extends Component {
state = {
root: new Node()
};
render() {
const { root } = this.state;
return (
<div>
<div>class component: {root.title}</div>
<button
onClick={() =>
this.setState(
produce((draft) => {
draft.root.title = "title changed";
})
)
}
>
change
</button>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
功能组件:
const FunctionTest = () => {
const [state, setState] = useState({ root: new Node() });
const { root } = state;
return (
<div>
<div>function component: {root.title}</div>
<button
onClick={() =>
setState(
produce((draft) => {
draft.root.title = "title changed";
})
)
}
>
change
</button>
</div>
);
};
Run Code Online (Sandbox Code Playgroud)
如何将沉浸状态迁移到钩子?
| 归档时间: |
|
| 查看次数: |
638 次 |
| 最近记录: |