gpt4 book ai didi

javascript - bindActionCreators,React-Redux 中的@connect 和理解代码

转载 作者:行者123 更新时间:2023-11-29 23:13:55 31 4
gpt4 key购买 nike

我试图在 github 上理解这段代码

程序员在这里使用了类似的东西

 constructor(props) {
super(props);
this.actions = bindActionCreators(Actions, this.props.dispatch);
}

问题 1:这里,this.actions = bindActionCreators(Actions, this.props.dispatch); 对我来说没有意义

此外,这不是主要问题,但从我学习 React-redux 的地方,我们曾经像这样连接组件

export default connect(mapStateToProps, 
{fetchCoin,
updateCrypto,
CurrencyRate,
CurrencyState
})(cryptoTicker);

在上面的代码片段中,程序员做了这样的事情

@connect(state => {
return {
score: state.game.get("score"),
result: state.game.get("result")
};
})

问题 2:** 这对我来说又有点陌生(就像我有几个月使用 js 的经验,但这是我第一次遇到 **@) 那么有人可以向我解释一下 JS 中的 @ 是什么吗?

最后,他声明了两个在类的返回语句之后调用 onclick 的函数

 _handleNewGame = () => {
this.actions.initGame();
}

/**
* Save the current game`s state.
*/
_handleSaveGame = () => {
this.actions.saveGame();
}

现在由于我对 JS 和 React 还比较陌生,所以这部分我有两个问题

问题 3:我们可以在 return 和 render 之后在类中创建一个函数吗?如果是,那么在声明所有其他函数的位置渲染之前创建一个函数(通常)不是一个好习惯吗?

最佳答案

对于问题 #1 和 #2,您的“@connect”和“connect(mapStateToProps, ...)(cryptoTicker)”语法是等效的。 @ 向解析器表明我们正在为我们的函数使用装饰器,即 connect(...) 函数,并输出相同的类,在本例中为 Game,但具有附加功能。这称为 HoC(高阶组件)设计模式,您可以在此处阅读更多相关信息 https://medium.com/@mappmechanic/react-utility-higher-order-components-as-decorators-tc39-stage-2-9e9f3a17688a

对于问题 #3,你是对的,最好将渲染函数留给组件中的最后一个函数。

关于javascript - bindActionCreators,React-Redux 中的@connect 和理解代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53310490/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com