是否可以在 useEffect 钩子中渲染组件?

Is it possible to render a component inside useEffect hook?

我只是想知道,是否可以在 useEffect 挂钩内渲染组件。 我有两个组件,比方说 A 和 B。 在组件 A 中,我的 useEffect 挂钩如下所示。 在 hook 中测试一些条件时,我想渲染一个组件 B。

export default function A() {
  const [location, setlocation] = usestate(null);
  useEffect(() => {
    if (condition) {
      <B />; // it does not render anything though
    } else {
      //code
    }
  }, [location]);
}

export default function B() {
  const test = () => {
    console.log("testing");
  };
  return (
    <View style={styles.container}>
      <Button title={"Click Me"} onPress={test} />
    </View>
  );
}

无论如何,这不是您想要使用的地方 useEffect

由于location是一个状态原子,它的改变会导致重新渲染,所以效果挂钩是不必要的。 (我假设 // code 比你在这里说的更复杂......)

对于等效但有效的示例,

export default function A() {
  const [location, setlocation] = useState(null);
  if (condition) {
    return <B />;
  }
  // code
  return null;
}

根据评论编辑

要强制重新呈现(卸载 + 重新挂载)组件,您可以为其使用任意键:

export default function A() {
  const [location, setlocation] = useState(null);
  React.useEffect(() => {
    // ....
  }, [location]);
  return <B key={location} />;
}

要强制它根据效果中的条件重新呈现,

export default function A() {
  const [location, setlocation] = useState(null);
  const [conditionCounter, setConditionCounter] = useState(0);
  React.useEffect(() => {
    if(condition) {
      setConditionCounter(c => c + 1);
    }
  }, [location]);
  return <B key={conditionCounter} />;
}

(或者可能只是 new Date()Math.random(),但计数器有效。)