Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更新接口元素以跟随React中的外部对象_Javascript_Reactjs - Fatal编程技术网

Javascript 更新接口元素以跟随React中的外部对象

Javascript 更新接口元素以跟随React中的外部对象,javascript,reactjs,Javascript,Reactjs,我很确定我的问题是标准的,但我没有找到答案。我创建了一个代码笔来说明它: 实际上,我正试图通过映射一个外部对象的属性,使我的接口与外部对象相对应。但我的界面不会在更改时自动更新。我可能错过了一个钩子什么的,但我找不到 谢谢你的帮助☺ class Example{ constructor(){ this.r = [1, 2, 3] } updateR = () =>{ this.r.pop() alert(this.r) } } function

我很确定我的问题是标准的,但我没有找到答案。我创建了一个代码笔来说明它:

实际上,我正试图通过映射一个外部对象的属性,使我的接口与外部对象相对应。但我的界面不会在更改时自动更新。我可能错过了一个钩子什么的,但我找不到

谢谢你的帮助☺

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'));
类示例{
构造函数(){
this.r=[1,2,3]
}  
更新程序=()=>{
这个.r.pop()
警报(this.r)
}
}
功能欢迎(道具){
常数e=新示例();
返回
哟
{
e、 r.map(条=>{
返回({bar})
})
}
}
常量元素=;
render(元素,document.getElementById('root');

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

要实现这一点,您需要使用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'));
类示例{
构造函数(){
this.r=[1,2,3]
}  
更新程序=()=>{
这个.r.pop()
警报(this.r)
归还这个;
}
}
功能欢迎(道具){
const[e,setE]=React.useState(新示例());
返回
setE({…e.updateR()})}>yo
{
e、 r.map(条=>{
返回({bar})
})
}
}
常量元素=;
render(元素,document.getElementById('root');
e
在每次渲染时都将“重置”为
new Example()
。您应该使用state,以便在单击时更新组件—尽管您必须以返回新对象的方式进行更新,而不是像
e.updateR()
那样修改现有对象。