[英]React setState is not accessible within lambda function
我正在尝试使用React.useContext
& React.useState
在反应项目中定义全局状态。
我目前有这样的事情:
# GlobalState.js
class GlobalState extends AbstractState {
register(current, setCurrent) {
this.current = current
this.setCurrent = setCurrent
}
...
}
const globalState = new GlobalState()
export default globalState
这是从 App 通过类似的东西传递的:
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
有任何想法,请告诉我
GlobalState.setCurrent
将是您尚未声明的类本身的静态方法。 它与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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.