如何在React Redux应用程序中使用装饰器? [英] How can I use decorators in a React Redux application?
问题描述
import React,{组件} from'react';
import {connect} from'react-redux';
@creatable
导出默认类BookDetails extends Component {
render(){
console.log(this.props);
if(!this.props.Activebook){
return< div>请选择书< / div>
}
return(
< div> {this.props.Activebook.title}< / div>
);
}
}
function creatable(){
return Create => {
@connect(state =>({Activebook:state.ActiveBook}))
class MyDecorator extends Component {
render(){
console.log('> >>>>>>>>>>>>');
console.log(this.props);
console.log('>>>>>>>>>>>>>')
return(
< div>
<创建
{... this.props}
/>
< / div>
)
}
}
return MyDecorator;
}
}
不幸的是上面的代码不起作用为什么?
请注意,我们不建议使用装饰器连接组件。
您不会在官方文档或示例中找到它们。
只是因为一些社区示例使用它们并不意味着它是一个好主意:规格仍在变化,工具支持是片状的,坦白说,您不需要 connect()
的装饰器,因为它们对简单的函数调用是荒谬的。 strong>
例如,而不是
@connect(mapStateToProps )
class MyComponent extends Component {}
你应该写
class MyComponent extends Component {}
MyComponent = connect(mapStateToProps)(MyComponent)
这样你就不用担心这些提案是语言的一部分。
我建议您遵守我们在官方Redux示例中使用的约定,并且对于a实施语法扩展。
I’m creating simple application using React Redux. I want to use decorator to inject some methods in my component.. I saw similar code in other projects:
import React, { Component } from 'react';
import { connect } from 'react-redux';
@creatable
export default class BookDetails extends Component {
render() {
console.log(this.props);
if (!this.props.Activebook) {
return <div> please select book</div>
}
return (
<div>{this.props.Activebook.title}</div>
);
}
}
function creatable() {
return Create => {
@connect(state=>({Activebook : state.ActiveBook}))
class MyDecorator extends Component {
render() {
console.log('>>>>>>>>>>>>>');
console.log(this.props);
console.log('>>>>>>>>>>>>>');
return (
<div>
<Create
{...this.props}
/>
</div>
)
}
}
return MyDecorator;
}
}
Unfortunately the above code is not working. Why?
Please note that we do not recommend using decorators for connecting components. You won’t find them anywhere in the official docs or examples.
Just because some community examples use them doesn’t mean it’s a good idea: the spec is still changing, the tooling support is flaky, and frankly, you don’t need decorators for connect()
because they desugar to simple function calls.
For example, rather than
@connect(mapStateToProps)
class MyComponent extends Component {}
you should write
class MyComponent extends Component {}
MyComponent = connect(mapStateToProps)(MyComponent)
This way you won’t have to worry about them breaking until the proposal is part of the language.
I recommend you to stick to the conventions we use in the official Redux examples and be very cautious about adopting experimental syntax extensions.
这篇关于如何在React Redux应用程序中使用装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!