阻止每次在渲染时调用函数

Dig*_*lMC 5 javascript reactjs

在我的 React.JS 应用程序中,我在功能组件内有一个函数,该函数在应用程序最初加载时呈现我需要的 JSX。问题是我不需要每次组件更新和return()调用方法时都重新运行它。此内容是通过 API 调用呈现的,并且不断重新运行的成本“昂贵”。

我如何限制其运行频率。

...

<Col lg="8">
    <div className="tab-content" id="newForm-wrapper">
        {/* !! STOP THIS FROM BEING CALLED EVERY RENDER !!! */}
        {renderSectionContent(formJSON)}
    </div>
</Col>

...
Run Code Online (Sandbox Code Playgroud)

下面是被调用的函数:

const renderSectionContent = json => {
    if (json.hasOwnProperty("form") && json.form.hasOwnProperty("sections")) {
        return json.form.sections.map((section, i) => {
            return <FormSection key={i} json={section} />;
        });
    } else {
        return <FormSection json={{}}/>;
    }
};
Run Code Online (Sandbox Code Playgroud)

Dev*_*mpo 4

为了防止每次渲染都运行此函数,您需要将函数的返回值存储在本地状态中。您可能希望每次 json 数据更改时都重新运行该函数,如果 json 具有深度嵌套的数据,这可能会很困难。根据您将 json 注入组件的方式,您设置状态的方式将会发生变化。

以下是假设数据作为 props 传递给类组件时如何完成此操作的示例:

export default class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sectionContent: renderSectionContent(props.formJson),
    };
  }

  renderSectionContent = json => {
    // do stuff
    return <FormSection />;
  }

  render() {
    return (
      <Col lg="8">
        <div className="tab-content" id="newForm-wrapper">
          {sectionContent}
        </div>
      </Col>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

或者使用 Hooks(React 版本 16.8 中的新功能):

export default function MyComponent(props) {
  const [sectionContent, setSectionContent] = useState(renderSectionContent(props.formJson));

  const renderSectionContent = json => {
    // do stuff
    return <FormSection />;
  }

  return (
    <Col lg="8">
      <div className="tab-content" id="newForm-wrapper">
        {sectionContent}
      </div>
    </Col>
  );
}
Run Code Online (Sandbox Code Playgroud)