【问题标题】:Update interface element to follow external Object in React更新界面元素以跟随 React 中的外部对象
【发布时间】:2021-04-26 17:29:39
【问题描述】:

我很确定我的问题是标准的,但我没有找到答案。我创建了一个 CodePen 来说明它:https://codepen.io/Hylectrif/pen/QWdoqNB?editors=1111.

我实际上是在尝试通过映射其中一个属性来使我的界面与外部对象相对应。但是我的界面不会自动更新更改。我可能错过了一个钩子或其他东西,但我找不到。

感谢您的帮助☺

class Example{
  constructor(){
    this.r = [1, 2, 3]
  }  
  updateR = () =>{
    this.r.pop()
    alert(this.r)
  }
}

function Welcome(props) {
  const e = new Example();
  return <React.Fragment>
    <button onClick={e.updateR}>yo</button>
    {
      e.r.map(bar => {
        return (<h1 key={bar}>{bar}</h1>)
      })
    }
  </React.Fragment>
}

const element = <Welcome />;
ReactDOM.render(element, document.getElementById('root'));

【问题讨论】:

  • e 在每次渲染时都“重置”为new Example()。您应该使用 state 来让您的组件在点击时更新 - 尽管您必须以返回新对象的方式执行此操作,而不是像 e.updateR() 那样改变现有对象。

标签: javascript reactjs


【解决方案1】:

您的组件永远不会重新渲染,因为您没有任何 props 更改,也没有触发更改检测的状态。

要完成这项工作,您需要使用 useState 挂钩并更新该状态中保存的对象。最好在组件内部而不是在另一个对象内部拥有功能。

虽然它不是最佳的,但这样的东西会起作用:

class Example{
  constructor(){
    this.r = [1, 2, 3]
  }  
  updateR = () =>{
    this.r.pop()
    alert(this.r)
    return this;
  }
}

function Welcome(props) {
  const [e, setE] = React.useState(new Example());  
  return <React.Fragment>
    <button onClick={() => setE({...e.updateR()})}>yo</button>
    {
      e.r.map(bar => {
        return (<h1 key={bar}>{bar}</h1>)
      })
    }
  </React.Fragment>
}

const element = <Welcome />;
ReactDOM.render(element, document.getElementById('root'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多