【问题标题】:Re-render a component in gatsby在 gatsby 中重新渲染组件
【发布时间】:2022-01-19 21:38:39
【问题描述】:

我正在使用 react,但我找不到如何在 gatsby 中条件渲染此示例。 主要目标是每次我更改值时重新渲染子组件,但我不想只重新渲染所有网站的子组件

import * as React from "react"
    
    let i=1;
    
    const Test = () => {
      return (
        
        <main>
        <button onClick={()=>{i=i+1;console.log(i) }}>CLICK ON ME</button>    
        <Child></Child>
        </main>  
               
                  
            
      )
    }
    
    export default Test
    
    const Child = () => {
        if(i===1){
            return(
            <div >
                1
                </div>
            )
        }
        if(i===2){
            return(
            <div >
                2
                </div>
            )
        }
        if(i===3){
            return(
            <div >
                3
                </div>
            )
        }
        else{
            return(
            <div >
                4+
                </div>
            )
        }
      
      
    
    
    }

【问题讨论】:

    标签: reactjs conditional-statements gatsby render


    【解决方案1】:

    Gatsby 是一个基于 React 的框架,它在底层使用 React,因此组件和状态管理与 Reacts 相同。

    在您的情况下,尝试使用useState 挂钩来呈现Child,将整数作为props 传递:

       const Test = () => {
         const [i, setI] = useState(1)
    
          return (
            <main>
            <button onClick={()=>{setI(i+ 1);console.log(i) }}>CLICK ON ME</button>    
            <Child i={i} />
            </main>  
          )
        }
    

    Child 组件中:

    const Child = ({ i }) => {
      return <div>{i}</div>
    }
    

    如果你想根据 i 值有条件地渲染不同的组件,只需使用:

    const Child = ({ i }) => {
      return <>
      {i==1 && <div>Some rendered content when i==1</div>}
      {i==2 && <div>Some rendered content when i==2</div>}
      </>
    }
    

    React 的状态管理只会再水化(渲染)已相应更改的所需部分。在这种情况下,因为您正在使用 setI 函数更改 i 值,所以它将重新水化使用 props 更改提升的值的孩子。

    【讨论】:

    • 我尝试了该解决方案,但出现此错误imgur.com/a/eGVx4MG ` 未处理的运行时错误关闭 在您的文件中发现一个未处理的运行时错误。请参阅下面的列表以修复它: ./node_modules/@babel/runtime/helpers/esm/readOnlyError.js:2 "i" is read-only ./node_modules/@babel/runtime/helpers/esm 中的函数 _readOnlyError 错误/readOnlyError.js:2 在编辑器 1 中打开 |导出默认函数 _readOnlyError(name) { > 2 | throw new TypeError("\"" + name + "\" 是只读的"); 3 | } `
    • 我解决了它,将 const 设置为 var 但我有一个问题,用户界面在点击时没有重新渲染,它在几次点击后重新渲染,恰好在 3 次点击之后
    • 你不应该,这个想法不是使用 const 或 vars,而是使用 React 的状态来强制重新渲染。 reactjs.org/docs/hooks-state.html
    猜你喜欢
    • 2020-11-16
    • 2021-03-19
    • 2019-06-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多