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

9

我有一个全局变量,它会经常改变。假设它存储在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.zare
2
全局变量的值是如何改变的? - Steven
尝试将箭头函数更改为普通函数。 因为在箭头函数中使用'this'不像预期的那样工作,它会指向外部对象。 - rahul_sann
它应该是一个 prop,就像 <MyComponent something={window.something} />。然后在你的组件中,const MyComponent = ({something}) => { React.useEffect(()=>{ // 当 something 改变时做一些事情 return () => {} ,[something]}) ...} - Rafael Mora
3个回答

1
这不会被存储对象的更改触发。如果您可以访问触发更改的进程,则让其调用状态更新。如果您没有访问权限,也许您可以定期轮询更改。个人而言,在需要时我只是从存储中获取它,或将其添加到状态并在会话的其余部分中使用。
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上设置事件监听器。


-1

像这样吗?

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

-1

你有两种方法可供选择:

  1. 每当全局变量更改时,重新渲染示例组件。这是一项昂贵的操作。
  2. 示例组件应监听 window.something 的更改。为此,应该有一些魔法,当 window.something 更改时更新示例组件状态。然后组件会平稳地更新。

我建议使用第二种方法,并使用像 Redux 这样的存储系统来实现那个魔法。


你能提供一个例子吗? - Malay M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接