Reactjs React-是否有类似的声明状态属性的方法?
因此,在新的ES6 React方式中,看到这样的事情非常常见:Reactjs React-是否有类似的声明状态属性的方法?,reactjs,ecmascript-6,redux,flux,Reactjs,Ecmascript 6,Redux,Flux,因此,在新的ES6 React方式中,看到这样的事情非常常见: render() const { thing1, thing2, thing3 } = this.props ...other stuff 对于状态属性是否有可比的方法(可能存在也可能不存在) 必须使用这样的状态变量会变得非常烦人: <h1>{this.state && this.state.title ? this.state.title : ''}</h1> {this.s
render()
const { thing1, thing2, thing3 } = this.props
...other stuff
对于状态属性是否有可比的方法(可能存在也可能不存在)
必须使用这样的状态变量会变得非常烦人:
<h1>{this.state && this.state.title ? this.state.title : ''}</h1>
{this.state&&this.state.title?this.state.title:'}
这实际上被称为分解分配,这是es6的一项功能,您可以在此处阅读:
您可以轻松地对任何对象执行以下操作:
const { title } = this.state
嗯,
如果在构造过程中给它一个值,那么这个.state
总是非空的。通常,您可以使用一个简单的| |
:this.state.title | | |“
来简化标题测试
下面是一个完整的示例:
class Foo extends React.Component {
static propTypes = {
thing1: PropTypes.string,
thing2: PropTypes.string.isRequired,
};
// initialize state during construction
state = { title: undefined, a: 1, b: 2 };
render() {
const { thing1, thing2 } = this.props;
const { title, a, b } = this.state;
return (
<div>
{thing1 && <div>{thing1}</div>}
<div>{thing2}</div> {/* isRequired so will never be null */}
<div>{title || ""}</div>
{a && <div>{a}</div>} {/* only render if a is truthy */}
<div>{b || "no b"}</div> {/* render "no b" if b not set */}
</div>
);
}
}
类Foo扩展了React.Component{
静态类型={
内容1:PropTypes.string,
thing2:PropTypes.string.isRequired,
};
//在构造期间初始化状态
state={title:undefined,a:1,b:2};
render(){
const{thing1,thing2}=this.props;
const{title,a,b}=this.state;
返回(
{thing1&&{thing1}
{thing2}{/*是必需的,因此永远不会为null*/}
{title | |”“}
{a&&{a}}{/*仅当a为truthy*/}时渲染
{b | |“无b”}{/*如果b未设置,则渲染“无b”*/}
);
}
}
哇,太棒了。很少有人能真正得到他们想要的答案。