我有一个全局变量,它会经常改变。假设它存储在window.something
中。在React中,我需要这个变化反映在组件以及其状态中。
示例代码:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { something: '1'}
}
render() {
return (
<div>
<input value={window.something}
onChange={event => {this.setState({'something': event.target.value})}}
/>
</div>
)
}
}
然而,该值仅在首次设置时更改,变量更新时不会有任何变化。
window.something
的值吗? - salman.zareprop
,就像<MyComponent something={window.something} />
。然后在你的组件中,const MyComponent = ({something}) => { React.useEffect(()=>{ // 当 something 改变时做一些事情 return () => {} ,[something]}) ...}
- Rafael Mora