在加载组件之前检查 prop 值

Check prop values before loading component

我有一个简单的 React 组件,可以将富文本编辑器 TinyMCE 的实例注入任何页面。

它正在工作,但有时错误的 prop 值会通过并导致错误。

我想知道,是否有一种方法可以在页面加载任何其他内容之前检查 planetIdplanetDescriptor 的值是否为空或 null。

我尝试将所有代码包装在其中:

if(props)
{
    const App = (props) => { ... }
}

但这总是会引发此错误:

ReferenceError: props is not defined

有没有办法在我完成加载组件之前检查 props 中的某些值?

谢谢!

这是应用程序:

const App = (props) => {
    const [planetDescriptor, setPlanetDescriptorState] = useState(props.planetDescriptor || "Planet Descriptor...");
    const [planetId, setPlanetIdState] = useState(props.planetId);
    const [planet, setPlanetState] = useState(props.planet);
    const [dataEditor, setDataEditor] = useState();

    const handleEditorChange = (data, editor) => {
        setDataEditor(data);
    }

    const updatePlanetDescriptor = (data) => {
        const request = axios.put(`/Planet/${planetId}/planetDescriptor`);
    }

    return (
        <Editor
            id={planetId.toString()}
            initialValue={planetDescriptor}
            init={{
                selector: ".planetDescriptor",
                menubar: 'edit table help'
            }}
            value={dataEditor}
            onEditorChange={handleEditorChange}
        />
    )
}

export default App;

你不能用你在使用 JSX 时尝试的方式包装代码,而不是普通的 javascript,所以你不能在那里使用 if 语句。

我建议使用三元组,像这样:

const SomeParentComponent = () => {
  const propsToPass = dataFetchOrWhatever;

  return (
    <>
      {propsToPass.planetDescriptor && propsToPass.planetId ?
        <App
          planetDescriptor={propsToPass.planetDescriptor}
          planetId={propsToPass.planetId}
          anyOtherProps={???}
        /> :
        null
      }
    </>
  )
};

这将有条件地渲染 App 组件,前提是这两个属性都存在。

也可以用&&达到同样的效果:

... code omitted ...
{propsToPass.planetDescriptor && propsToPass.planetId &&
  <App
    planetDescriptor={propsToPass.planetDescriptor}
    planetId={propsToPass.planetId}
    anyOtherProps={???}
  />
}
... code omitted ...

您使用哪种方法很大程度上取决于偏好和代码库的一致性。

你在条件句中的想法是正确的。只需要将它放在组件中而不是包装整个东西。您可以尝试的是类似于 react docs for conditional rendering 的示例。它的作用是检查 props = null / undefined 然后 returns 或呈现错误状态。否则它 returns 编辑器。

    if (!props) {
      return <h1>error state</h1>
    }
    return <Editor></Editor>