【问题标题】:Swapping ReactJS functional component on state change在状态更改时交换 ReactJS 功能组件
【发布时间】:2021-08-17 22:40:25
【问题描述】:

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

我有以下几点:

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并改变组件?

【问题讨论】:

    标签: reactjs components state react-functional-component


    【解决方案1】:
    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>
      )
     }
    }
    

    【讨论】:

    • 谢谢,这个想法奏效了,但不是说setPage={setPage},我不得不使用callback={setPage}
    【解决方案2】:

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

    useEffect Doc

    它是说状态变化何时“起作用”。

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2020-05-12
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      相关资源
      最近更新 更多