在不更改条件的情况下对状态更改进行条件重新渲染

时间:2019-09-23 07:25:47

标签: javascript reactjs

我有一个条件,可以显示编辑器,而某个道具仍然为真。事实是,每次我选择另一个用于填充该编辑器的对象时,用于呈现该编辑器的数据都将发生变化。

但是,由于负责条件渲染的prop不会改变,即使用来渲染编辑器的数据也不会改变,所以它拒绝在状态改变时重新渲染。

我不是特别擅长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>
    );
  }
}

3 个答案:

答案 0 :(得分:0)

是否有必要单独设置状态?为什么不

handleShowEditor = routine => {
    this.setState({ 
        showEditor: true,
        editorObject: routine
    });
};

Keep in mind setState是异步的,您的实现可能导致这种奇怪的行为。

答案 1 :(得分:0)

如果您仍在寻找答案,我在使用相同的 [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 组件状态并执行重新渲染,否则将 prevData 原样分配,不会导致重新渲染。

希望有帮助。

编辑:

答案 2 :(得分:-1)

由于setState是异步的,因此您可以在其回调中进行另一个调用。

尝试这样

handleShowEditor = routine => {
this.setState({ 
    showEditor: true
}, () =>{
     this.setState({
       editorObject: routine
     )}
});
};
相关问题