reactjs 无法在lambda函数中访问React setState

d7v8vwbk  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(126)

我正在尝试使用React.useContext&React.useState在react项目中定义一个全局状态。
我目前有这样的东西:

# GlobalState.js
class GlobalState extends AbstractState {
   register(current, setCurrent) {
      this.current = current
      this.setCurrent = setCurrent
   }
   ...
}

const globalState = new GlobalState()
export default globalState

这是从应用程序传递的,如下所示:

const [current, setCurrent] = React.useState({})
globalState.register_state(current, setCurrent)
const state = {current: current, setCurrent: setCurrent}
return React.createElement(GlobalContext.Provider, {value: state},
    ...children
)

并且它在某些点被如下使用:

class WebRequestsTimeChart extends React.Component {

render(){
    ...
    return React.createElement(GlobalContext.Consumer, null, (state) => {
        return this.#getChart(state)
    })
}

componentDidMount() {
   console.log(GlobalState.setCurrent) // actual react dispatch content
}

componentWillUnmount() {
   console.log(GlobalState.setCurrent) // actual react dispatch content
}

#getChart(state) {
   console.log(GlobalState.setCurrent) // actual react dispatch content
   return React.createElement(VictoryChart, {
       ...
       containerComponent: React.createElement(VictoryZoomVoronoiContainer, {
           ...
           events: {
              onClick: (event) => {
                  console.log(state.setCurrent) // actual react dispatch content
                  console.log(GlobalState.setCurrent) // f(){} <--- ???
              }
           }
       }
   }
}


因此,传递给onClick的lambda无法访问GlobalState.setCurrent,但它访问state.setCurrent没有问题。如果我定义另一个类似GlobalState.someRandomMethod的方法,onClick仍然可以访问它。React.useState返回的setCurrent的行为似乎不同。我还意识到这个方法不能被复制(例如,structuredClone不适用于此)。我考虑的另一个问题是Difference between class object Method declaration React?,但我不确定这将如何导致GlobalState.setCurrent的行为不同。
添加以下内容也不会更改此行为:

constructor(props) {
        super(props);
        this.getChart = this.getChart.bind(this).bind(GlobalState);
    }

如果您对正在发生的事情有任何想法,以及如何在onClick中使用GlobalState.setCurrent,请告诉我

ikfrs5lh

ikfrs5lh1#

GlobalState.setCurrent将是一个static method on the class itself,你还没有声明,它和setCurrent示例方法不是一回事。

class Foo {
  bar () {
    return 'bar';
  }
}

console.log(Foo.bar?.()); // undefined. "bar" doesn't exist on the class itself.

const foo = new Foo();
console.log(foo.bar()) // 'bar'; exists on instance of Foo.

class Baz {
  static boom () {
    return "static boom";
  }
  
  boom () {
    return "instance boom";
  }
}

console.log(Baz.boom()); // static boom
const baz = new Baz();
console.log(baz.boom()); // instance boom

相关问题