Reactjs immer财产变更不存在';功能组件中的t触发器更新
我将节点实体存储在状态中。单击按钮时,我想更改属性“title”,并触发组件更新以显示新的标题值。 函数组件中没有发生任何事情,它只在类组件中更新 类组件:Reactjs immer财产变更不存在';功能组件中的t触发器更新,reactjs,react-hooks,immer.js,Reactjs,React Hooks,Immer.js,我将节点实体存储在状态中。单击按钮时,我想更改属性“title”,并触发组件更新以显示新的标题值。 函数组件中没有发生任何事情,它只在类组件中更新 类组件: class ClassTest extends Component { state = { root: new Node() }; render() { const { root } = this.state; return ( <div> <div>
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>
);
}
}
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>
);
};
class类测试扩展组件{
状态={
根:新节点()
};
render(){
const{root}=this.state;
返回(
类组件:{root.title}
这是我的国家(
制作((草稿)=>{
draft.root.title=“标题已更改”;
})
)
}
>
改变
);
}
}
功能组件:
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>
);
}
}
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>
);
};
const FunctionTest=()=>{
const[state,setState]=useState({root:new Node()});
const{root}=状态;
返回(
函数组件:{root.title}
设定状态(
制作((草稿)=>{
draft.root.title=“标题已更改”;
})
)
}
>
改变
);
};
如何将immer状态迁移到hooks?不确定immer到底发生了什么,但是如果您将一个浅层
title
属性添加到状态
,然后更新它draft.title='new value'代码>将触发更改并进行渲染。问题似乎出在您的新节点()
实例上。您的immer代码很好,因为它可以处理简单的对象。您应该检查节点实例是否state.root
。