在状态更改时交换 ReactJS 功能组件

Swapping ReactJS functional component on state change

我是新来的反应和努力改变组件的状态,并在改变时替换内容。

我有以下内容:

function App() {

 const [page, setPage] = React.useState('list');

 switch(page) {
  case 'A':
   return(
   <body> 
    <Home />
    <A />
   </body>
  )
  case 'B':
  return(
   <body> 
    <Home />
    <B />
   </body>
  )
 }
}

function A() {
 
 return (
  <div>
   <div onClick={() => setPage('B')}>GoToB</div>
  </div>
 )
}

function B() {
    return (
       <div>test</div>
    )
}

有一个单独的 Home 组件可以正确显示。如何正确调用 setPage 函数来更改状态,以便触发 switch case 并更改组件?

function App() {

 const [page, setPage] = React.useState('list');

function A({setPage}) {
 
 return (
  <div>
   <div onClick={() => setPage('compsci')}>GoToB</div>
  </div>
 )
}

function B({setPage}) {
    return (
      <div>
   <div onClick={() => setPage('list')}>GoToB</div>
  </div>
    )
}

 switch(page) {
  case 'list':
   return(
   <body> 
    <Home />
    <A setPage={setPage}/>
   </body>
  )
  case 'compsci':
  return(
   <body> 
    <Home />
    <B setPage={setPage} />
   </body>
  )
 }
}

有一个 Hook 是为它构建的,他的名字叫 useEffect。

useEffect Doc

它说的是状态更改何时“起作用”。