[英]How to re-render React components without actually changing state
[英]React re-render conditional on state change without changing the conditional
我有一个条件显示一个编辑器,而某个道具仍然是真实的。 问题是,每次我使用 select 另一个 object 来填充该编辑器时,该编辑器所使用的数据都应该更改。
但是,由于负责条件渲染的道具没有改变,即使渲染编辑器的数据发生了变化,它也拒绝在 state 更改时重新渲染。
我不是特别擅长 React,所以,希望有人能解释我如何解决这个小问题。
条件渲染
{this.state.showEditor ? (<BlockEditor routine={this.state.editorObject} />) : null}
被调用的方法。
handleShowEditor = routine => {
this.setState({ showEditor: true });
this.setState({ editorObject: routine });
};
编辑器组件
export default class BlockEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
routine: this.props.routine
};
}
render() {
return (
<div>
<Editor
autofocus
holderId="editorjs-container"
onChange={data => this.handleSave(data)}
customTools={{}}
onReady={() => console.log("Start!")}
data={this.props.routine.description}
instanceRef={instance => (this.editorInstance = instance)}
/>
</div>
);
}
}
是否有单独设置 state 的理由? 为什么不
handleShowEditor = routine => {
this.setState({
showEditor: true,
editorObject: routine
});
};
请记住, setState
是异步的,您的实现可能会导致这种奇怪的行为。
如果您仍在寻找答案,我在使用相同的 [Editor.JS][1] 时遇到了同样的问题:)。
这对我有用的功能组件:
// on change fires when component re-intialize
onChange={async (e) => {
const newData = await e.saver.save();
setEditorData((prevData) => {
console.log(prevData.blocks);
console.log(newData.blocks);
if (
JSON.stringify(prevData.blocks) === JSON.stringify(newData.blocks)
) {
console.log("no data changed");
return prevData;
} else {
console.log("data changed");
return newData;
}
});
}}
// setting true to re-render when currentPage data change
enableReInitialize={true}
在这里,我们只是检查数据更改是否将其分配给 editorData 组件 state 并执行重新渲染,否则按原样分配 prevData,这不会导致重新渲染。
希望能帮助到你。
编辑:
由于setState
是异步的,您可以在其回调中进行另一个调用。
像这样试试
handleShowEditor = routine => {
this.setState({
showEditor: true
}, () =>{
this.setState({
editorObject: routine
)}
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.