javascript && 运算符如何工作

How does a javascript && operator work

我想将 prop 传递给 React 组件,以父组件状态中的布尔值为条件,该组件希望将 myProp 作为 object,propTypes 冲突如下:

//component's code
class MyComponent extends Component {

    ...
    static propTypes = {
        myProp: propTypes.object
    }
    ...
}

现在,我要传递如下道具:

//Parent component's code
class ParentComponent extends Component {
    constructor() {
        super();
        this.state = {
          par: true,
        }
    }
    render(){
        const obj = {
            key1: 'value1',
            key2: 'value2'
        }
        ...
        return ( 
            <MyComponent
                myProp = {this.state.par && obj}
            />
        )
    }
...
}

执行上面的代码会在浏览器控制台中发出以下警告:

Warning: Failed prop type: Invalid prop myProp of type boolean supplied to MyComponent, expected object.

如果 this.state.parfalse,则 this.state.par && objfalse(布尔值,不是对象)。

您可能需要条件运算符:

return ( 
    <MyComponent
        myProp = {this.state.par ? obj : null}
    />
)

现在,无论标志如何,您都提供了 objectobjnull)类型的内容。

或者更隐晦一点,添加一个 ||:

return ( 
    <MyComponent
        myProp = {this.state.par && obj || null}
    />
)

...但我会使用条件句。


当然,MyComponent 需要明白 myProp 可能是 null...

我会将布尔值作为 属性 包含在 obj 中,并检查子组件中的值

render() {
   const obj = {
        key1: 'value1',
        key2: 'value2'
        par: this.state.par
    }
   return(
       <MyComponent myProp={obj} />
   );
}

并处理子组件中的true/falsiness。

在你的情况下 myProp = {this.state.par && obj} 如果 this.state.par 为假并且存在 obj 则布尔值 false 将被返回而不是 obj,你应该这样写

myProp = {this.state.par? obj: null}

根据 docs:

true && expression always evaluates to expression, and false && expression always evaluates to false.

Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.