簡體   English   中英

從Window函數更新React / Redux狀態

[英]Updating React/Redux State from Window function

我有一種情況,我試圖從放置在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 /> ) } } 

this在您的函數內部不可訪問,您需要將其綁定。

嘗試:

class MyComponent extends Component {

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

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

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

}

如果您想通過某種操作來更新Redux狀態(這是通過設計更新Redux狀態的唯一方法),則需要使用connect(mapStateToProps,mapDispatchToProps)(Component )

上面有關將windowFunction轉換為箭頭函數的評論之一解決了該問題。 謝謝!

 class MyComponent extends Component { updateRedux = a => { console.log(a) } componentDidMount() { window.windowFunction = a => { this.updateRedux(a) }.bind(this) } render() { return ( <Stuff /> ) } } 

您可以做的是使用演示者和連接的組件,使用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每個實例重新定義了這可能不是您想要的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM