全局变量更改时更新react组件状态

时间:2018-03-28 05:30:03

标签: javascript reactjs

我有一个经常变化的全局变量。假设它存储在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>
    )
  }
}

但是,该值仅在第一次设置,并且在变量更新时没有变化。

4 个答案:

答案 0 :(得分:1)

window.something作为道具传递给Example组件。

Example

的变化
class Example extends React.Component {
    render() {
      return (
        <div>
          <input value={this.props.something}
                 onChange={(event) => { this.props.onChange(event.target.value) }}
          />
        </div>
      )
    }
}

致电Example

<Example something={window.something}
   onChange={(value) => {window.something = value}} />

答案 1 :(得分:0)

这样的东西?

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 :(得分:0)

您的案例有两种方法:

  1. 每当全局变量发生更改时,重新呈现Example组件。这是一项代价高昂的操作。
  2. 示例组件应该监听window.something中的更改。为此,当window.something改变时,应该有一些魔法可以更新你的Example组件状态。然后,组件可以顺利更新。
  3. 我建议使用第二种方法并使用像Redux这样的商店系统来实现这种魔力。

答案 3 :(得分:0)

这不会因更改存储对象而触发。如果您有权访问触发更改的过程,请让它调用状态更新。如果您没有访问权限,也许您可​​以经常轮询更改。

我个人只是从需要它的页面上的存储中获取它,或者将其添加到状态中并将其用于会话的其余部分。

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);
    } 
}

Here是一个链接,说明如何在浏览器的localStorage上设置事件侦听器。