从Window函数更新React / Redux状态

问题描述 投票:0回答:4

我有一个场景,我正在尝试从放置在Window上的函数更新React / Redux状态。窗口上的函数无法访问React组件中的函数。知道如何在这种设置中绑定该功能吗?这个代码片段只有一个控制台日志,Redux调用将在此处进行。

class MyComponent extends Component {
  

  updateRedux = a => {
    console.log(a)
  }

  componentDidMount() {
    window.windowFunction = function(a) {
      this.updateRedux(a)
    }    
  }

  render() {
    return (
      <Stuff />
    )
  }

}
javascript reactjs
4个回答
0
投票

你的函数内部无法访问this,你需要绑定它。

试试:

class MyComponent extends Component {

  updateRedux = a => {
    console.log(a)
  }

  componentDidMount() {
    window.windowFunction = function(a) {
      this.updateRedux(a)
    }.bind(this)
  }

  render() {
    return (
      <Stuff />
    )
  }

}

0
投票

如果你的意思是你想用一些动作来更新Redux状态(这是通过设计更新Redux状态的唯一方法),那么你需要使用connect(mapStateToProps,mapDispatchToProps)将这个动作及其功能提供给你的Component(组件) )


0
投票

上面关于将windowFunction转换为箭头函数的评论之一解决了这个问题。谢谢!

class MyComponent extends Component {

  updateRedux = a => {
    console.log(a)
  }

  componentDidMount() {
    window.windowFunction = a => {
      this.updateRedux(a)
    }.bind(this)
  }

  render() {
    return (
      <Stuff />
    )
  }

}

0
投票

您可以做的是使用react-redux使用演示者和连接组件分离关注点。我假设您知道这个库,如果您需要更多详细信息,请发表评论。

// Simple "presenter", the getComponentData is used to get the data for the
// redux store.
class MyComponentPresenter extends Component {

  // returns data for redux
  getComponentData () {}

  componentDidMount() {
    this.props.updateRedux(this); // update Redux
  }

  render() {
    return (
      <Stuff />
    )
  }

}


// This component has the exact same interface, but comes with a updateRedux
// props which automatically dispatches an action
export const MyComponent = connect(null, {
  updateRedux(componentInstance) {
    return {
      type: "updateRedux"
    };
  }
});

// in the reducer
//
function reducer (state, action) {
  switch (action.type) {
    case "updateRedux":
      return ...
  }
}

不再需要全局可用的功能(在您的示例中为MyComponents的每个实例重新定义,这可能不是您想要的)。

© www.soinside.com 2019 - 2024. All rights reserved.