我很确定我的问题是标准的,但我没有找到答案。我创建了一个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'));
您的组件永远不会被重新渲染,因为您没有任何道具更改,也没有触发更改检测的状态。
要实现这一点,您需要使用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'));