[英]Updating the react component state when a global variable changes
我有一個經常更改的全局變量。 假設它存儲在window.something
。 在反應中,我需要將此更改反映到組件及其狀態中。
示例代碼:
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>
)
}
}
但是,該值僅是第一次設置,並且隨着變量的更新而沒有變化。
更改存儲對象不會觸發此操作。 如果您有權訪問觸發更改的過程,請讓它調用狀態更新。 如果您沒有訪問權限,也許您可以經常輪詢更改。
就個人而言,我只是從需要它的頁面上的存儲中獲取它,或者將其添加到狀態中並在其余的會話中使用它。
componentWillMount = () => {
const foo = JSON.parse(sessionStorage.getItem('foo'));
const bar = JSON.parse(sessionStorage.getItem('bar'));
if (!isEmpty(foo) && !isEmpty(bar)) {
this.props.setFoo(foo);
this.props.setBar(bar);
}
}
這是一個鏈接,說明如何在瀏覽器的localStorage上設置事件偵聽器。
像這樣嗎
window.something='1234';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { something: window.something}
}
render() {
return (
<div>
<input defaultValue={window.something}
value={this.state.something}
onChange={event => {this.setState({'something': event.target.value})}}
/>
</div>
)
}
}
您的情況有2種方法:
我建議第二種方法,並使用像Redux這樣的存儲系統來實現這種魔力。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.