【问题标题】:React - is there a similar way of declaring state properties?React - 是否有类似的声明状态属性的方式?
【发布时间】:2016-12-18 07:37:31
【问题描述】:

所以,在新的 ES6 React 方式中,看到这样的事情是很常见的:

render()

  const { thing1, thing2, thing3 } = this.props

  ...other stuff

对于可能存在或不存在的状态属性,是否有可比较的方法?

不得不像这样使用状态变量会很烦人:

<h1>{this.state && this.state.title ? this.state.title : ''}</h1>

【问题讨论】:

    标签: reactjs ecmascript-6 redux flux


    【解决方案1】:

    这实际上称为解构赋值,它是一个 es6 功能,您可以在此处阅读: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

    您可以轻松地对任何对象执行以下操作:

    const { title } = this.state
    

    【讨论】:

    • 哇,太棒了。很少有人能真正得到他们想要的答案。
    【解决方案2】:

    好吧,this.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>
            );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多